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,38 @@
/**
* External dependencies
*/
import { getSetting } from '@woocommerce/settings';
export const blockName = 'woocommerce/checkout';
export const blockAttributes = {
hasDarkControls: {
type: 'boolean',
default: getSetting( 'hasDarkEditorStyleSupport', false ),
},
showRateAfterTaxName: {
type: 'boolean',
default: getSetting( 'displayCartPricesIncludingTax', false ),
},
};
/**
* @deprecated here for v1 migration support
*/
export const deprecatedAttributes = {
showOrderNotes: {
type: 'boolean',
default: true,
},
showPolicyLinks: {
type: 'boolean',
default: true,
},
showReturnToCart: {
type: 'boolean',
default: true,
},
cartPageId: {
type: 'number',
default: 0,
},
};

View File

@@ -0,0 +1,46 @@
{
"name": "woocommerce/checkout",
"version": "1.0.0",
"title": "Checkout",
"description": "Display a checkout form so your customers can submit orders.",
"category": "woocommerce",
"keywords": [ "WooCommerce" ],
"supports": {
"align": [ "wide" ],
"html": false,
"multiple": false
},
"attributes": {
"isPreview": {
"type": "boolean",
"default": false,
"save": false
},
"showCompanyField": {
"type": "boolean",
"default": false
},
"requireCompanyField": {
"type": "boolean",
"default": false
},
"allowCreateAccount": {
"type": "boolean",
"default": false
},
"showApartmentField": {
"type": "boolean",
"default": true
},
"showPhoneField": {
"type": "boolean",
"default": true
},
"requirePhoneField": {
"type": "boolean",
"default": false
}
},
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,193 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import classnames from 'classnames';
import { createInterpolateElement, useEffect } from '@wordpress/element';
import { useStoreCart } from '@woocommerce/base-context/hooks';
import {
useCheckoutContext,
useValidationContext,
ValidationContextProvider,
CheckoutProvider,
SnackbarNoticesContainer,
} from '@woocommerce/base-context';
import { StoreNoticesContainer } from '@woocommerce/base-context/providers';
import BlockErrorBoundary from '@woocommerce/base-components/block-error-boundary';
import { SidebarLayout } from '@woocommerce/base-components/sidebar-layout';
import { CURRENT_USER_IS_ADMIN, getSetting } from '@woocommerce/settings';
import { SlotFillProvider } from '@woocommerce/blocks-checkout';
import withScrollToTop from '@woocommerce/base-hocs/with-scroll-to-top';
/**
* Internal dependencies
*/
import './styles/style.scss';
import EmptyCart from './empty-cart';
import CheckoutOrderError from './checkout-order-error';
import { LOGIN_TO_CHECKOUT_URL, isLoginRequired, reloadPage } from './utils';
import type { Attributes } from './types';
import { CheckoutBlockContext } from './context';
import { hasNoticesOfType } from '../../utils/notices';
import { StoreNoticesProvider } from '../../base/context/providers';
const LoginPrompt = () => {
return (
<>
{ __(
'You must be logged in to checkout. ',
'woo-gutenberg-products-block'
) }
<a href={ LOGIN_TO_CHECKOUT_URL }>
{ __(
'Click here to log in.',
'woo-gutenberg-products-block'
) }
</a>
</>
);
};
const Checkout = ( {
attributes,
children,
}: {
attributes: Attributes;
children: React.ReactChildren;
} ): JSX.Element => {
const { hasOrder, customerId } = useCheckoutContext();
const { cartItems, cartIsLoading } = useStoreCart();
const {
allowCreateAccount,
showCompanyField,
requireCompanyField,
showApartmentField,
showPhoneField,
requirePhoneField,
} = attributes;
if ( ! cartIsLoading && cartItems.length === 0 ) {
return <EmptyCart />;
}
if ( ! hasOrder ) {
return <CheckoutOrderError />;
}
if (
isLoginRequired( customerId ) &&
allowCreateAccount &&
getSetting( 'checkoutAllowsSignup', false )
) {
<LoginPrompt />;
}
return (
<CheckoutBlockContext.Provider
value={ {
allowCreateAccount,
showCompanyField,
requireCompanyField,
showApartmentField,
showPhoneField,
requirePhoneField,
} }
>
{ children }
</CheckoutBlockContext.Provider>
);
};
const ScrollOnError = ( {
scrollToTop,
}: {
scrollToTop: ( props: Record< string, unknown > ) => void;
} ): null => {
const { hasError: checkoutHasError, isIdle: checkoutIsIdle } =
useCheckoutContext();
const { hasValidationErrors, showAllValidationErrors } =
useValidationContext();
const hasErrorsToDisplay =
checkoutIsIdle &&
checkoutHasError &&
( hasValidationErrors || hasNoticesOfType( 'wc/checkout', 'default' ) );
useEffect( () => {
let scrollToTopTimeout: number;
if ( hasErrorsToDisplay ) {
showAllValidationErrors();
// Scroll after a short timeout to allow a re-render. This will allow focusableSelector to match updated components.
scrollToTopTimeout = window.setTimeout( () => {
scrollToTop( {
focusableSelector: 'input:invalid, .has-error input',
} );
}, 50 );
}
return () => {
clearTimeout( scrollToTopTimeout );
};
}, [ hasErrorsToDisplay, scrollToTop, showAllValidationErrors ] );
return null;
};
const Block = ( {
attributes,
children,
scrollToTop,
}: {
attributes: Attributes;
children: React.ReactChildren;
scrollToTop: ( props: Record< string, unknown > ) => void;
} ): JSX.Element => {
return (
<BlockErrorBoundary
header={ __(
'Something went wrong…',
'woo-gutenberg-products-block'
) }
text={ createInterpolateElement(
__(
'The checkout has encountered an unexpected error. <button>Try reloading the page</button>. If the error persists, please get in touch with us so we can assist.',
'woo-gutenberg-products-block'
),
{
button: (
<button
className="wc-block-link-button"
onClick={ reloadPage }
/>
),
}
) }
showErrorMessage={ CURRENT_USER_IS_ADMIN }
>
<SnackbarNoticesContainer context="wc/checkout" />
<StoreNoticesProvider>
<StoreNoticesContainer context="wc/checkout" />
<ValidationContextProvider>
{ /* SlotFillProvider need to be defined before CheckoutProvider so fills have the SlotFill context ready when they mount. */ }
<SlotFillProvider>
<CheckoutProvider>
<SidebarLayout
className={ classnames( 'wc-block-checkout', {
'has-dark-controls':
attributes.hasDarkControls,
} ) }
>
<Checkout attributes={ attributes }>
{ children }
</Checkout>
<ScrollOnError scrollToTop={ scrollToTop } />
</SidebarLayout>
</CheckoutProvider>
</SlotFillProvider>
</ValidationContextProvider>
</StoreNoticesProvider>
</BlockErrorBoundary>
);
};
export default withScrollToTop( Block );

View File

@@ -0,0 +1,8 @@
export const PRODUCT_OUT_OF_STOCK = 'woocommerce_rest_product_out_of_stock';
export const PRODUCT_NOT_PURCHASABLE =
'woocommerce_rest_product_not_purchasable';
export const PRODUCT_NOT_ENOUGH_STOCK =
'woocommerce_rest_product_partially_out_of_stock';
export const PRODUCT_SOLD_INDIVIDUALLY =
'woocommerce_rest_product_too_many_in_cart';
export const GENERIC_CART_ITEM_ERROR = 'woocommerce_rest_cart_item_error';

View File

@@ -0,0 +1,138 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { CART_URL } from '@woocommerce/block-settings';
import { removeCart } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
import { getSetting } from '@woocommerce/settings';
import { decodeEntities } from '@wordpress/html-entities';
/**
* Internal dependencies
*/
import './style.scss';
import {
PRODUCT_OUT_OF_STOCK,
PRODUCT_NOT_PURCHASABLE,
PRODUCT_NOT_ENOUGH_STOCK,
PRODUCT_SOLD_INDIVIDUALLY,
GENERIC_CART_ITEM_ERROR,
} from './constants';
const cartItemErrorCodes = [
PRODUCT_OUT_OF_STOCK,
PRODUCT_NOT_PURCHASABLE,
PRODUCT_NOT_ENOUGH_STOCK,
PRODUCT_SOLD_INDIVIDUALLY,
GENERIC_CART_ITEM_ERROR,
];
const preloadedCheckoutData = getSetting( 'checkoutData', {} );
/**
* When an order was not created for the checkout, for example, when an item
* was out of stock, this component will be shown instead of the checkout form.
*
* The error message is derived by the hydrated API request passed to the
* checkout block.
*/
const CheckoutOrderError = () => {
const checkoutData = {
code: '',
message: '',
...( preloadedCheckoutData || {} ),
};
const errorData = {
code: checkoutData.code || 'unknown',
message:
decodeEntities( checkoutData.message ) ||
__(
'There was a problem checking out. Please try again. If the problem persists, please get in touch with us so we can assist.',
'woocommerce'
),
};
return (
<div className="wc-block-checkout-error">
<Icon
className="wc-block-checkout-error__image"
icon={ removeCart }
size={ 100 }
/>
<ErrorTitle errorData={ errorData } />
<ErrorMessage errorData={ errorData } />
<ErrorButton errorData={ errorData } />
</div>
);
};
/**
* Get the error message to display.
*
* @param {Object} props Incoming props for the component.
* @param {Object} props.errorData Object containing code and message.
*/
const ErrorTitle = ( { errorData } ) => {
let heading = __( 'Checkout error', 'woocommerce' );
if ( cartItemErrorCodes.includes( errorData.code ) ) {
heading = __(
'There is a problem with your cart',
'woocommerce'
);
}
return (
<strong className="wc-block-checkout-error_title">{ heading }</strong>
);
};
/**
* Get the error message to display.
*
* @param {Object} props Incoming props for the component.
* @param {Object} props.errorData Object containing code and message.
*/
const ErrorMessage = ( { errorData } ) => {
let message = errorData.message;
if ( cartItemErrorCodes.includes( errorData.code ) ) {
message =
message +
' ' +
__(
'Please edit your cart and try again.',
'woocommerce'
);
}
return <p className="wc-block-checkout-error__description">{ message }</p>;
};
/**
* Get the CTA button to display.
*
* @param {Object} props Incoming props for the component.
* @param {Object} props.errorData Object containing code and message.
*/
const ErrorButton = ( { errorData } ) => {
let buttonText = __( 'Retry', 'woocommerce' );
let buttonUrl = 'javascript:window.location.reload(true)';
if ( cartItemErrorCodes.includes( errorData.code ) ) {
buttonText = __( 'Edit your cart', 'woocommerce' );
buttonUrl = CART_URL;
}
return (
<span className="wp-block-button">
<a href={ buttonUrl } className="wp-block-button__link">
{ buttonText }
</a>
</span>
);
};
export default CheckoutOrderError;

View File

@@ -0,0 +1,21 @@
.wc-block-checkout-error {
padding: $gap-largest;
text-align: center;
width: 100%;
.wc-block-checkout-error__image {
max-width: 150px;
margin: 0 auto 1em;
display: block;
color: inherit;
}
.wc-block-checkout-error__title {
display: block;
margin: 0;
font-weight: bold;
}
.wc-block-checkout-error__description {
display: block;
margin: 0.25em 0 1em 0;
}
}

View File

@@ -0,0 +1,57 @@
/**
* External dependencies
*/
import { createContext, useContext } from '@wordpress/element';
/**
* Context consumed by inner blocks.
*/
export type CheckoutBlockContextProps = {
allowCreateAccount: boolean;
showCompanyField: boolean;
showApartmentField: boolean;
showPhoneField: boolean;
requireCompanyField: boolean;
requirePhoneField: boolean;
showOrderNotes: boolean;
showPolicyLinks: boolean;
showReturnToCart: boolean;
cartPageId: number;
showRateAfterTaxName: boolean;
};
export type CheckoutBlockControlsContextProps = {
addressFieldControls: () => JSX.Element | null;
accountControls: () => JSX.Element | null;
};
export const CheckoutBlockContext = createContext< CheckoutBlockContextProps >(
{
allowCreateAccount: false,
showCompanyField: false,
showApartmentField: false,
showPhoneField: false,
requireCompanyField: false,
requirePhoneField: false,
showOrderNotes: true,
showPolicyLinks: true,
showReturnToCart: true,
cartPageId: 0,
showRateAfterTaxName: false,
}
);
export const CheckoutBlockControlsContext =
createContext< CheckoutBlockControlsContextProps >( {
addressFieldControls: () => null,
accountControls: () => null,
} );
export const useCheckoutBlockContext = (): CheckoutBlockContextProps => {
return useContext( CheckoutBlockContext );
};
export const useCheckoutBlockControlsContext =
(): CheckoutBlockControlsContextProps => {
return useContext( CheckoutBlockControlsContext );
};

View File

@@ -0,0 +1,292 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import classnames from 'classnames';
import {
InnerBlocks,
useBlockProps,
InspectorControls,
} from '@wordpress/block-editor';
import { SidebarLayout } from '@woocommerce/base-components/sidebar-layout';
import {
CheckoutProvider,
EditorProvider,
useEditorContext,
} from '@woocommerce/base-context';
import {
previewCart,
previewSavedPaymentMethods,
} from '@woocommerce/resource-previews';
import {
PanelBody,
ToggleControl,
Notice,
CheckboxControl,
} from '@wordpress/components';
import { CartCheckoutFeedbackPrompt } from '@woocommerce/editor-components/feedback-prompt';
import { CHECKOUT_PAGE_ID } from '@woocommerce/block-settings';
import { createInterpolateElement } from '@wordpress/element';
import { getAdminLink } from '@woocommerce/settings';
import { CartCheckoutCompatibilityNotice } from '@woocommerce/editor-components/compatibility-notices';
import type { TemplateArray } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import './inner-blocks';
import './styles/editor.scss';
import {
addClassToBody,
useBlockPropsWithLocking,
} from '../cart-checkout-shared';
import { CheckoutBlockContext, CheckoutBlockControlsContext } from './context';
import type { Attributes } from './types';
// This is adds a class to body to signal if the selected block is locked
addClassToBody();
// Array of allowed block names.
const ALLOWED_BLOCKS: string[] = [
'woocommerce/checkout-fields-block',
'woocommerce/checkout-totals-block',
];
const BlockSettings = ( {
attributes,
setAttributes,
}: {
attributes: Attributes;
setAttributes: ( attributes: Record< string, unknown > ) => undefined;
} ): JSX.Element => {
const { hasDarkControls } = attributes;
const { currentPostId } = useEditorContext();
return (
<InspectorControls>
{ currentPostId !== CHECKOUT_PAGE_ID && (
<Notice
className="wc-block-checkout__page-notice"
isDismissible={ false }
status="warning"
>
{ createInterpolateElement(
__(
'If you would like to use this block as your default checkout you must update your <a>page settings in WooCommerce</a>.',
'woo-gutenberg-products-block'
),
{
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', 'woo-gutenberg-products-block' ) }>
<ToggleControl
label={ __(
'Dark mode inputs',
'woo-gutenberg-products-block'
) }
help={ __(
'Inputs styled specifically for use on dark background colors.',
'woo-gutenberg-products-block'
) }
checked={ hasDarkControls }
onChange={ () =>
setAttributes( {
hasDarkControls: ! hasDarkControls,
} )
}
/>
</PanelBody>
<CartCheckoutFeedbackPrompt />
</InspectorControls>
);
};
export const Edit = ( {
attributes,
setAttributes,
}: {
attributes: Attributes;
setAttributes: ( attributes: Record< string, unknown > ) => undefined;
} ): JSX.Element => {
const {
allowCreateAccount,
showCompanyField,
requireCompanyField,
showApartmentField,
showPhoneField,
requirePhoneField,
showOrderNotes,
showPolicyLinks,
showReturnToCart,
showRateAfterTaxName,
cartPageId,
} = attributes;
const defaultTemplate = [
[ 'woocommerce/checkout-fields-block', {}, [] ],
[ 'woocommerce/checkout-totals-block', {}, [] ],
] as TemplateArray;
const toggleAttribute = ( key: keyof Attributes ): void => {
const newAttributes = {} as Partial< Attributes >;
newAttributes[ key ] = ! ( attributes[ key ] as boolean );
setAttributes( newAttributes );
};
const accountControls = (): JSX.Element => (
<InspectorControls>
<PanelBody
title={ __(
'Account options',
'woo-gutenberg-products-block'
) }
>
<ToggleControl
label={ __(
'Allow shoppers to sign up for a user account during checkout',
'woo-gutenberg-products-block'
) }
checked={ allowCreateAccount }
onChange={ () =>
setAttributes( {
allowCreateAccount: ! allowCreateAccount,
} )
}
/>
</PanelBody>
</InspectorControls>
);
const addressFieldControls = (): JSX.Element => (
<InspectorControls>
<PanelBody
title={ __( 'Address Fields', 'woo-gutenberg-products-block' ) }
>
<p className="wc-block-checkout__controls-text">
{ __(
'Show or hide fields in the checkout address forms.',
'woo-gutenberg-products-block'
) }
</p>
<ToggleControl
label={ __( 'Company', 'woo-gutenberg-products-block' ) }
checked={ showCompanyField }
onChange={ () => toggleAttribute( 'showCompanyField' ) }
/>
{ showCompanyField && (
<CheckboxControl
label={ __(
'Require company name?',
'woo-gutenberg-products-block'
) }
checked={ requireCompanyField }
onChange={ () =>
toggleAttribute( 'requireCompanyField' )
}
className="components-base-control--nested"
/>
) }
<ToggleControl
label={ __(
'Apartment, suite, etc.',
'woo-gutenberg-products-block'
) }
checked={ showApartmentField }
onChange={ () => toggleAttribute( 'showApartmentField' ) }
/>
<ToggleControl
label={ __( 'Phone', 'woo-gutenberg-products-block' ) }
checked={ showPhoneField }
onChange={ () => toggleAttribute( 'showPhoneField' ) }
/>
{ showPhoneField && (
<CheckboxControl
label={ __(
'Require phone number?',
'woo-gutenberg-products-block'
) }
checked={ requirePhoneField }
onChange={ () =>
toggleAttribute( 'requirePhoneField' )
}
className="components-base-control--nested"
/>
) }
</PanelBody>
</InspectorControls>
);
const blockProps = useBlockPropsWithLocking();
return (
<div { ...blockProps }>
<EditorProvider
previewData={ { previewCart, previewSavedPaymentMethods } }
>
<BlockSettings
attributes={ attributes }
setAttributes={ setAttributes }
/>
<CheckoutProvider>
<SidebarLayout
className={ classnames( 'wc-block-checkout', {
'has-dark-controls': attributes.hasDarkControls,
} ) }
>
<CheckoutBlockControlsContext.Provider
value={ {
addressFieldControls,
accountControls,
} }
>
<CheckoutBlockContext.Provider
value={ {
allowCreateAccount,
showCompanyField,
requireCompanyField,
showApartmentField,
showPhoneField,
requirePhoneField,
showOrderNotes,
showPolicyLinks,
showReturnToCart,
cartPageId,
showRateAfterTaxName,
} }
>
<InnerBlocks
allowedBlocks={ ALLOWED_BLOCKS }
template={ defaultTemplate }
templateLock="insert"
/>
</CheckoutBlockContext.Provider>
</CheckoutBlockControlsContext.Provider>
</SidebarLayout>
</CheckoutProvider>
</EditorProvider>
<CartCheckoutCompatibilityNotice blockName="checkout" />
</div>
);
};
export const Save = (): JSX.Element => {
return (
<div
{ ...useBlockProps.save( {
className: 'wc-block-checkout is-loading',
} ) }
>
<InnerBlocks.Content />
</div>
);
};

View File

@@ -0,0 +1,42 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { SHOP_URL } from '@woocommerce/block-settings';
import { cart } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
/**
* Internal dependencies
*/
import './style.scss';
const EmptyCart = () => {
return (
<div className="wc-block-checkout-empty">
<Icon
className="wc-block-checkout-empty__image"
icon={ cart }
size={ 100 }
/>
<strong className="wc-block-checkout-empty__title">
{ __( 'Your cart is empty!', 'woocommerce' ) }
</strong>
<p className="wc-block-checkout-empty__description">
{ __(
"Checkout is not available whilst your cart is empty—please take a look through our store and come back when you're ready to place an order.",
'woocommerce'
) }
</p>
{ SHOP_URL && (
<span className="wp-block-button">
<a href={ SHOP_URL } className="wp-block-button__link">
{ __( 'Browse store', 'woocommerce' ) }
</a>
</span>
) }
</div>
);
};
export default EmptyCart;

View File

@@ -0,0 +1,21 @@
.wc-block-checkout-empty {
padding: $gap-largest;
text-align: center;
width: 100%;
.wc-block-checkout-empty__image {
max-width: 150px;
margin: 0 auto 1em;
display: block;
color: inherit;
}
.wc-block-checkout-empty__title {
display: block;
margin: 0;
font-weight: bold;
}
.wc-block-checkout-empty__description {
display: block;
margin: 0.25em 0 1em 0;
}
}

View File

@@ -0,0 +1,35 @@
/**
* External dependencies
*/
import { InnerBlocks, useBlockProps } from '@wordpress/block-editor';
/**
* Internal dependencies
*/
import './editor.scss';
import { useForcedLayout, getAllowedBlocks } from '../../cart-checkout-shared';
export const AdditionalFields = ( {
block,
}: {
// Name of the parent block.
block: string;
} ): JSX.Element => {
const { 'data-block': clientId } = useBlockProps();
const allowedBlocks = getAllowedBlocks( block );
useForcedLayout( {
clientId,
registeredBlocks: allowedBlocks,
} );
return (
<div className="wc-block-checkout__additional_fields">
<InnerBlocks allowedBlocks={ allowedBlocks } />
</div>
);
};
export const AdditionalFieldsContent = (): JSX.Element => (
<InnerBlocks.Content />
);

View File

@@ -0,0 +1,32 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
const attributes = ( {
defaultTitle = __( 'Step', 'woo-gutenberg-products-block' ),
defaultDescription = __(
'Step description text.',
'woo-gutenberg-products-block'
),
defaultShowStepNumber = true,
}: {
defaultTitle: string;
defaultDescription: string;
defaultShowStepNumber?: boolean;
} ): Record< string, Record< string, unknown > > => ( {
title: {
type: 'string',
default: defaultTitle,
},
description: {
type: 'string',
default: defaultDescription,
},
showStepNumber: {
type: 'boolean',
default: defaultShowStepNumber,
},
} );
export default attributes;

View File

@@ -0,0 +1,12 @@
.wc-block-checkout__additional_fields {
margin: 1.5em 0 0;
}
.wc-block-components-checkout-step__description-placeholder {
opacity: 0.5;
}
.wc-block-components-checkout-step__title {
display: flex;
width: 100%;
}

View File

@@ -0,0 +1,97 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import classnames from 'classnames';
import {
PlainText,
InspectorControls,
useBlockProps,
} from '@wordpress/block-editor';
import { PanelBody, ToggleControl } from '@wordpress/components';
/**
* Internal dependencies
*/
import FormStepHeading from './form-step-heading';
export interface FormStepBlockProps {
attributes: { title: string; description: string; showStepNumber: boolean };
setAttributes: ( attributes: Record< string, unknown > ) => void;
className?: string;
children?: React.ReactNode;
lock?: { move: boolean; remove: boolean };
}
/**
* Form Step Block for use in the editor.
*/
export const FormStepBlock = ( {
attributes,
setAttributes,
className = '',
children,
}: FormStepBlockProps ): JSX.Element => {
const { title = '', description = '', showStepNumber = true } = attributes;
const blockProps = useBlockProps( {
className: classnames( 'wc-block-components-checkout-step', className, {
'wc-block-components-checkout-step--with-step-number':
showStepNumber,
} ),
} );
return (
<div { ...blockProps }>
<InspectorControls>
<PanelBody
title={ __(
'Form Step Options',
'woo-gutenberg-products-block'
) }
>
<ToggleControl
label={ __(
'Show step number',
'woo-gutenberg-products-block'
) }
checked={ showStepNumber }
onChange={ () =>
setAttributes( {
showStepNumber: ! showStepNumber,
} )
}
/>
</PanelBody>
</InspectorControls>
<FormStepHeading>
<PlainText
className={ '' }
value={ title }
onChange={ ( value ) => setAttributes( { title: value } ) }
/>
</FormStepHeading>
<div className="wc-block-components-checkout-step__container">
<p className="wc-block-components-checkout-step__description">
<PlainText
className={
! description
? 'wc-block-components-checkout-step__description-placeholder'
: ''
}
value={ description }
placeholder={ __(
'Optional text for this form step.',
'woo-gutenberg-products-block'
) }
onChange={ ( value ) =>
setAttributes( {
description: value,
} )
}
/>
</p>
<div className="wc-block-components-checkout-step__content">
{ children }
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,32 @@
/**
* External dependencies
*/
import Title from '@woocommerce/base-components/title';
/**
* Step Heading Component
*/
const FormStepHeading = ( {
children,
stepHeadingContent,
}: {
children: JSX.Element;
stepHeadingContent?: JSX.Element;
} ): JSX.Element => (
<div className="wc-block-components-checkout-step__heading">
<Title
aria-hidden="true"
className="wc-block-components-checkout-step__title"
headingLevel="2"
>
{ children }
</Title>
{ !! stepHeadingContent && (
<span className="wc-block-components-checkout-step__heading-content">
{ stepHeadingContent }
</span>
) }
</div>
);
export default FormStepHeading;

View File

@@ -0,0 +1,4 @@
export * from './attributes';
export * from './form-step-block';
export * from './form-step-heading';
export * from './additional-fields';

View File

@@ -0,0 +1,66 @@
/**
* External dependencies
*/
import { Children, cloneElement, isValidElement } from '@wordpress/element';
import { getValidBlockAttributes } from '@woocommerce/base-utils';
import { useStoreCart } from '@woocommerce/base-context';
import {
useCheckoutExtensionData,
useValidation,
} from '@woocommerce/base-context/hooks';
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';
import metadata from './block.json';
const getProps = ( el: Element ) => {
return {
attributes: getValidBlockAttributes(
{ ...metadata.attributes, ...blockAttributes },
/* eslint-disable @typescript-eslint/no-explicit-any */
( el instanceof HTMLElement ? el.dataset : {} ) as any
),
};
};
const Wrapper = ( {
children,
}: {
children: React.ReactChildren;
} ): React.ReactNode => {
// we need to pluck out receiveCart.
// eslint-disable-next-line no-unused-vars
const { extensions, receiveCart, ...cart } = useStoreCart();
const checkoutExtensionData = useCheckoutExtensionData();
const validation = useValidation();
return Children.map( children, ( child ) => {
if ( isValidElement( child ) ) {
const componentProps = {
extensions,
cart,
checkoutExtensionData,
validation,
};
return cloneElement( child, componentProps );
}
return child;
} );
};
renderParentBlock( {
Block,
blockName,
selector: '.wp-block-woocommerce-checkout',
getProps,
blockMap: getRegisteredBlockComponents( blockName ) as Record<
string,
React.ReactNode
>,
blockWrapper: Wrapper,
} );

View File

@@ -0,0 +1,143 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { fields } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
import { createBlock } from '@wordpress/blocks';
import type { BlockInstance } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import { blockAttributes, deprecatedAttributes } from './attributes';
import './inner-blocks';
import metadata from './block.json';
const settings = {
icon: {
src: (
<Icon
icon={ fields }
className="wc-block-editor-components-block-icon"
/>
),
},
attributes: {
...metadata.attributes,
...blockAttributes,
...deprecatedAttributes,
},
edit: Edit,
save: Save,
// Migrates v1 to v2 checkout.
deprecated: [
{
attributes: {
...metadata.attributes,
...blockAttributes,
...deprecatedAttributes,
},
save( { attributes }: { attributes: { className: string } } ) {
return (
<div
className={ classnames(
'is-loading',
attributes.className
) }
/>
);
},
migrate: ( attributes: {
showOrderNotes: boolean;
showPolicyLinks: boolean;
showReturnToCart: boolean;
cartPageId: number;
} ) => {
const {
showOrderNotes,
showPolicyLinks,
showReturnToCart,
cartPageId,
} = attributes;
return [
attributes,
[
createBlock(
'woocommerce/checkout-fields-block',
{},
[
createBlock(
'woocommerce/checkout-express-payment-block',
{},
[]
),
createBlock(
'woocommerce/checkout-contact-information-block',
{},
[]
),
createBlock(
'woocommerce/checkout-shipping-address-block',
{},
[]
),
createBlock(
'woocommerce/checkout-billing-address-block',
{},
[]
),
createBlock(
'woocommerce/checkout-shipping-methods-block',
{},
[]
),
createBlock(
'woocommerce/checkout-payment-block',
{},
[]
),
showOrderNotes
? createBlock(
'woocommerce/checkout-order-note-block',
{},
[]
)
: false,
showPolicyLinks
? createBlock(
'woocommerce/checkout-terms-block',
{},
[]
)
: false,
createBlock(
'woocommerce/checkout-actions-block',
{
showReturnToCart,
cartPageId,
},
[]
),
].filter( Boolean ) as BlockInstance[]
),
createBlock( 'woocommerce/checkout-totals-block', {} ),
],
];
},
isEligible: (
attributes: Record< string, unknown >,
innerBlocks: BlockInstance[]
) => {
return ! innerBlocks.some(
( block: { name: string } ) =>
block.name === 'woocommerce/checkout-fields-block'
);
},
},
],
};
registerFeaturePluginBlockType( metadata, settings );

View File

@@ -0,0 +1,21 @@
export default {
cartPageId: {
type: 'number',
default: 0,
},
showReturnToCart: {
type: 'boolean',
default: true,
},
className: {
type: 'string',
default: '',
},
lock: {
type: 'object',
default: {
move: true,
remove: true,
},
},
};

View File

@@ -0,0 +1,27 @@
{
"name": "woocommerce/checkout-actions-block",
"version": "1.0.0",
"title": "Actions",
"description": "Allow customers to place 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/checkout-fields-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,39 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { getSetting } from '@woocommerce/settings';
import {
PlaceOrderButton,
ReturnToCartButton,
} from '@woocommerce/base-components/cart-checkout';
/**
* Internal dependencies
*/
import './style.scss';
const Block = ( {
cartPageId,
showReturnToCart,
className,
}: {
cartPageId: number;
showReturnToCart: boolean;
className?: string;
} ): JSX.Element => {
return (
<div
className={ classnames( 'wc-block-checkout__actions', className ) }
>
{ showReturnToCart && (
<ReturnToCartButton
link={ getSetting( 'page-' + cartPageId, false ) }
/>
) }
<PlaceOrderButton />
</div>
);
};
export default Block;

View File

@@ -0,0 +1,98 @@
/**
* External dependencies
*/
import { useRef } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import PageSelector from '@woocommerce/editor-components/page-selector';
import { PanelBody, ToggleControl } from '@wordpress/components';
import { CHECKOUT_PAGE_ID } from '@woocommerce/block-settings';
import Noninteractive from '@woocommerce/base-components/noninteractive';
/**
* Internal dependencies
*/
import Block from './block';
export const Edit = ( {
attributes,
setAttributes,
}: {
attributes: {
showReturnToCart: boolean;
cartPageId: number;
};
setAttributes: ( attributes: Record< string, unknown > ) => void;
} ): JSX.Element => {
const blockProps = useBlockProps();
const { cartPageId = 0, showReturnToCart = true } = attributes;
const { current: savedCartPageId } = useRef( cartPageId );
const currentPostId = useSelect(
( select ) => {
if ( ! savedCartPageId ) {
const store = select( 'core/editor' );
return store.getCurrentPostId();
}
return savedCartPageId;
},
[ savedCartPageId ]
);
return (
<div { ...blockProps }>
<InspectorControls>
<PanelBody
title={ __(
'Account options',
'woo-gutenberg-products-block'
) }
>
<ToggleControl
label={ __(
'Show a "Return to Cart" link',
'woo-gutenberg-products-block'
) }
checked={ showReturnToCart }
onChange={ () =>
setAttributes( {
showReturnToCart: ! showReturnToCart,
} )
}
/>
</PanelBody>
{ showReturnToCart &&
! (
currentPostId === CHECKOUT_PAGE_ID &&
savedCartPageId === 0
) && (
<PageSelector
pageId={ cartPageId }
setPageId={ ( id: number ) =>
setAttributes( { cartPageId: id } )
}
labels={ {
title: __(
'Return to Cart button',
'woo-gutenberg-products-block'
),
default: __(
'WooCommerce Cart Page',
'woo-gutenberg-products-block'
),
} }
/>
) }
</InspectorControls>
<Noninteractive>
<Block
showReturnToCart={ showReturnToCart }
cartPageId={ cartPageId }
/>
</Noninteractive>
</div>
);
};
export const Save = (): JSX.Element => {
return <div { ...useBlockProps.save() } />;
};

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,26 @@
/**
* External dependencies
*/
import { Icon, button } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
/**
* Internal dependencies
*/
import attributes from './attributes';
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ button }
className="wc-block-editor-components-block-icon"
/>
),
},
attributes,
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,39 @@
.wc-block-checkout__actions {
display: flex;
justify-content: space-between;
align-items: center;
.wc-block-components-checkout-place-order-button {
width: 50%;
padding: 1em;
height: auto;
.wc-block-components-button__text {
line-height: 24px;
> svg {
fill: $white;
vertical-align: top;
}
}
}
}
.is-mobile {
.wc-block-checkout__actions {
.wc-block-components-checkout-return-to-cart-button {
display: none;
}
.wc-block-components-checkout-place-order-button {
width: 100%;
}
}
}
.is-large {
.wc-block-checkout__actions {
@include with-translucent-border(1px 0 0);
padding: em($gap-large) 0;
}
}

View File

@@ -0,0 +1,30 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import formStepAttributes from '../../form-step/attributes';
export default {
...formStepAttributes( {
defaultTitle: __( 'Billing address', 'woo-gutenberg-products-block' ),
defaultDescription: __(
'Enter the address that matches your card or payment method.',
'woo-gutenberg-products-block'
),
} ),
className: {
type: 'string',
default: '',
},
lock: {
type: 'object',
default: {
move: true,
remove: true,
},
},
};

View File

@@ -0,0 +1,27 @@
{
"name": "woocommerce/checkout-billing-address-block",
"version": "1.0.0",
"title": "Billing Address",
"description": "Collect your customer's billing address.",
"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/checkout-fields-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,103 @@
/**
* External dependencies
*/
import { useMemo, useEffect, Fragment } from '@wordpress/element';
import {
useCheckoutAddress,
useStoreEvents,
useEditorContext,
} from '@woocommerce/base-context';
import { AddressForm } from '@woocommerce/base-components/cart-checkout';
import Noninteractive from '@woocommerce/base-components/noninteractive';
import type {
BillingAddress,
AddressField,
AddressFields,
} from '@woocommerce/settings';
/**
* Internal dependencies
*/
import PhoneNumber from '../../phone-number';
const Block = ( {
showCompanyField = false,
showApartmentField = false,
showPhoneField = false,
requireCompanyField = false,
requirePhoneField = false,
}: {
showCompanyField: boolean;
showApartmentField: boolean;
showPhoneField: boolean;
requireCompanyField: boolean;
requirePhoneField: boolean;
} ): JSX.Element => {
const {
defaultAddressFields,
billingAddress,
setBillingAddress,
setBillingPhone,
} = useCheckoutAddress();
const { dispatchCheckoutEvent } = useStoreEvents();
const { isEditor } = useEditorContext();
// Clears data if fields are hidden.
useEffect( () => {
if ( ! showPhoneField ) {
setBillingPhone( '' );
}
}, [ showPhoneField, setBillingPhone ] );
const addressFieldsConfig = useMemo( () => {
return {
company: {
hidden: ! showCompanyField,
required: requireCompanyField,
},
address_2: {
hidden: ! showApartmentField,
},
};
}, [
showCompanyField,
requireCompanyField,
showApartmentField,
] ) as Record< keyof AddressFields, Partial< AddressField > >;
const AddressFormWrapperComponent = isEditor ? Noninteractive : Fragment;
return (
<AddressFormWrapperComponent>
<AddressForm
id="billing"
type="billing"
onChange={ ( values: Partial< BillingAddress > ) => {
setBillingAddress( values );
dispatchCheckoutEvent( 'set-billing-address' );
} }
values={ billingAddress }
fields={
Object.keys(
defaultAddressFields
) as ( keyof AddressFields )[]
}
fieldConfig={ addressFieldsConfig }
/>
{ showPhoneField && (
<PhoneNumber
isRequired={ requirePhoneField }
value={ billingAddress.phone }
onChange={ ( value ) => {
setBillingPhone( value );
dispatchCheckoutEvent( 'set-phone-number', {
step: 'billing',
} );
} }
/>
) }
</AddressFormWrapperComponent>
);
};
export default Block;

View File

@@ -0,0 +1,78 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { useBlockProps } from '@wordpress/block-editor';
import { useCheckoutAddress } from '@woocommerce/base-context/hooks';
import { innerBlockAreas } from '@woocommerce/blocks-checkout';
/**
* Internal dependencies
*/
import {
FormStepBlock,
AdditionalFields,
AdditionalFieldsContent,
} from '../../form-step';
import {
useCheckoutBlockContext,
useCheckoutBlockControlsContext,
} from '../../context';
import Block from './block';
export const Edit = ( {
attributes,
setAttributes,
}: {
attributes: {
title: string;
description: string;
showStepNumber: boolean;
className: string;
};
setAttributes: ( attributes: Record< string, unknown > ) => void;
} ): JSX.Element | null => {
const {
showCompanyField,
showApartmentField,
requireCompanyField,
showPhoneField,
requirePhoneField,
} = useCheckoutBlockContext();
const { addressFieldControls: Controls } =
useCheckoutBlockControlsContext();
const { showBillingFields } = useCheckoutAddress();
if ( ! showBillingFields ) {
return null;
}
return (
<FormStepBlock
setAttributes={ setAttributes }
attributes={ attributes }
className={ classnames(
'wc-block-checkout__billing-fields',
attributes?.className
) }
>
<Controls />
<Block
showCompanyField={ showCompanyField }
showApartmentField={ showApartmentField }
requireCompanyField={ requireCompanyField }
showPhoneField={ showPhoneField }
requirePhoneField={ requirePhoneField }
/>
<AdditionalFields block={ innerBlockAreas.BILLING_ADDRESS } />
</FormStepBlock>
);
};
export const Save = (): JSX.Element => {
return (
<div { ...useBlockProps.save() }>
<AdditionalFieldsContent />
</div>
);
};

View File

@@ -0,0 +1,68 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { withFilteredAttributes } from '@woocommerce/shared-hocs';
import { FormStep } from '@woocommerce/base-components/cart-checkout';
import { useCheckoutContext } from '@woocommerce/base-context';
import { useCheckoutAddress } from '@woocommerce/base-context/hooks';
/**
* Internal dependencies
*/
import Block from './block';
import attributes from './attributes';
import { useCheckoutBlockContext } from '../../context';
const FrontendBlock = ( {
title,
description,
showStepNumber,
children,
className,
}: {
title: string;
description: string;
showStepNumber: boolean;
children: JSX.Element;
className?: string;
} ): JSX.Element | null => {
const { isProcessing: checkoutIsProcessing } = useCheckoutContext();
const {
requireCompanyField,
requirePhoneField,
showApartmentField,
showCompanyField,
showPhoneField,
} = useCheckoutBlockContext();
const { showBillingFields } = useCheckoutAddress();
if ( ! showBillingFields ) {
return null;
}
return (
<FormStep
id="billing-fields"
disabled={ checkoutIsProcessing }
className={ classnames(
'wc-block-checkout__billing-fields',
className
) }
title={ title }
description={ description }
showStepNumber={ showStepNumber }
>
<Block
requireCompanyField={ requireCompanyField }
showApartmentField={ showApartmentField }
showCompanyField={ showCompanyField }
showPhoneField={ showPhoneField }
requirePhoneField={ requirePhoneField }
/>
{ children }
</FormStep>
);
};
export default withFilteredAttributes( attributes )( FrontendBlock );

View File

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

View File

@@ -0,0 +1,33 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import formStepAttributes from '../../form-step/attributes';
export default {
...formStepAttributes( {
defaultTitle: __(
'Contact information',
'woo-gutenberg-products-block'
),
defaultDescription: __(
"We'll use this email to send you details and updates about your order.",
'woo-gutenberg-products-block'
),
} ),
className: {
type: 'string',
default: '',
},
lock: {
type: 'object',
default: {
remove: true,
move: true,
},
},
};

View File

@@ -0,0 +1,27 @@
{
"name": "woocommerce/checkout-contact-information-block",
"version": "1.0.0",
"title": "Contact Information",
"description": "Collect your customer's contact information.",
"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/checkout-fields-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,64 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { ValidatedTextInput } from '@woocommerce/base-components/text-input';
import {
useCheckoutContext,
useCheckoutAddress,
useStoreEvents,
} from '@woocommerce/base-context';
import { getSetting } from '@woocommerce/settings';
import { CheckboxControl } from '@woocommerce/blocks-checkout';
/**
* Internal dependencies
*/
const Block = ( {
allowCreateAccount,
}: {
allowCreateAccount: boolean;
} ): JSX.Element => {
const { customerId, shouldCreateAccount, setShouldCreateAccount } =
useCheckoutContext();
const { billingAddress, setEmail } = useCheckoutAddress();
const { dispatchCheckoutEvent } = useStoreEvents();
const onChangeEmail = ( value ) => {
setEmail( value );
dispatchCheckoutEvent( 'set-email-address' );
};
const createAccountUI = ! customerId &&
allowCreateAccount &&
getSetting( 'checkoutAllowsGuest', false ) &&
getSetting( 'checkoutAllowsSignup', false ) && (
<CheckboxControl
className="wc-block-checkout__create-account"
label={ __(
'Create an account?',
'woo-gutenberg-products-block'
) }
checked={ shouldCreateAccount }
onChange={ ( value ) => setShouldCreateAccount( value ) }
/>
);
return (
<>
<ValidatedTextInput
id="email"
type="email"
label={ __( 'Email address', 'woo-gutenberg-products-block' ) }
value={ billingAddress.email }
autoComplete="email"
onChange={ onChangeEmail }
required={ true }
/>
{ createAccountUI }
</>
);
};
export default Block;

View File

@@ -0,0 +1,61 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { useBlockProps } from '@wordpress/block-editor';
import { innerBlockAreas } from '@woocommerce/blocks-checkout';
import Noninteractive from '@woocommerce/base-components/noninteractive';
/**
* Internal dependencies
*/
import {
FormStepBlock,
AdditionalFields,
AdditionalFieldsContent,
} from '../../form-step';
import Block from './block';
import {
useCheckoutBlockContext,
useCheckoutBlockControlsContext,
} from '../../context';
export const Edit = ( {
attributes,
setAttributes,
}: {
attributes: {
title: string;
description: string;
showStepNumber: boolean;
className: string;
};
setAttributes: ( attributes: Record< string, unknown > ) => void;
} ): JSX.Element => {
const { allowCreateAccount } = useCheckoutBlockContext();
const { accountControls: Controls } = useCheckoutBlockControlsContext();
return (
<FormStepBlock
attributes={ attributes }
setAttributes={ setAttributes }
className={ classnames(
'wc-block-checkout__contact-fields',
attributes?.className
) }
>
<Controls />
<Noninteractive>
<Block allowCreateAccount={ allowCreateAccount } />
</Noninteractive>
<AdditionalFields block={ innerBlockAreas.CONTACT_INFORMATION } />
</FormStepBlock>
);
};
export const Save = (): JSX.Element => {
return (
<div { ...useBlockProps.save() }>
<AdditionalFieldsContent />
</div>
);
};

View File

@@ -0,0 +1,53 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { withFilteredAttributes } from '@woocommerce/shared-hocs';
import { FormStep } from '@woocommerce/base-components/cart-checkout';
import { useCheckoutContext } from '@woocommerce/base-context';
/**
* Internal dependencies
*/
import Block from './block';
import attributes from './attributes';
import LoginPrompt from './login-prompt';
import { useCheckoutBlockContext } from '../../context';
const FrontendBlock = ( {
title,
description,
showStepNumber,
children,
className,
}: {
title: string;
description: string;
allowCreateAccount: boolean;
showStepNumber: boolean;
children: JSX.Element;
className?: string;
} ) => {
const { isProcessing: checkoutIsProcessing } = useCheckoutContext();
const { allowCreateAccount } = useCheckoutBlockContext();
return (
<FormStep
id="contact-fields"
disabled={ checkoutIsProcessing }
className={ classnames(
'wc-block-checkout__contact-fields',
className
) }
title={ title }
description={ description }
showStepNumber={ showStepNumber }
stepHeadingContent={ () => <LoginPrompt /> }
>
<Block allowCreateAccount={ allowCreateAccount } />
{ children }
</FormStep>
);
};
export default withFilteredAttributes( attributes )( FrontendBlock );

View File

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

View File

@@ -0,0 +1,33 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { getSetting } from '@woocommerce/settings';
import { useCheckoutContext } from '@woocommerce/base-context';
import { LOGIN_URL } from '@woocommerce/block-settings';
const LOGIN_TO_CHECKOUT_URL = `${ LOGIN_URL }?redirect_to=${ encodeURIComponent(
window.location.href
) }`;
const LoginPrompt = () => {
const { customerId } = useCheckoutContext();
if ( ! getSetting( 'checkoutShowLoginReminder', true ) || customerId ) {
return null;
}
return (
<>
{ __(
'Already have an account? ',
'woocommerce'
) }
<a href={ LOGIN_TO_CHECKOUT_URL }>
{ __( 'Log in.', 'woocommerce' ) }
</a>
</>
);
};
export default LoginPrompt;

View File

@@ -0,0 +1,31 @@
{
"name": "woocommerce/checkout-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": {
"className": {
"type": "string",
"default": ""
},
"lock": {
"type": "object",
"default": {
"remove": true,
"move": true
}
}
},
"parent": [ "woocommerce/checkout-fields-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

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

View File

@@ -0,0 +1,91 @@
/**
* 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;
lock: {
move: boolean;
remove: boolean;
};
};
} ): JSX.Element | null => {
const { paymentMethods, isInitialized } = useExpressPaymentMethods();
const hasExpressPaymentMethods = Object.keys( paymentMethods ).length > 0;
const blockProps = useBlockProps( {
className: classnames(
{
'wp-block-woocommerce-checkout-express-payment-block--has-express-payment-methods':
hasExpressPaymentMethods,
},
attributes?.className
),
attributes,
} );
if ( ! isInitialized ) {
return null;
}
return (
<div { ...blockProps }>
{ hasExpressPaymentMethods ? (
<Block />
) : (
<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-checkout-express-payment-block {
margin: 14px 0 28px;
.components-placeholder__label svg {
font-size: 1em;
}
.wc-block-components-express-payment-continue-rule--checkout {
margin-bottom: 0;
}
&.wp-block-woocommerce-checkout-express-payment-block--has-express-payment-methods {
padding: 14px 0;
margin: -14px 0 14px 0 !important;
position: relative;
}
}
.wp-block-woocommerce-checkout-express-payment-block-placeholder {
* {
pointer-events: all; // Overrides parent disabled component in editor context
}
.wp-block-woocommerce-checkout-express-payment-block-placeholder__description {
display: block;
margin: 0 0 1em;
}
}

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,31 @@
{
"name": "woocommerce/checkout-fields-block",
"version": "1.0.0",
"title": "Checkout Fields",
"description": "Column containing checkout address fields.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false,
"inserter": false,
"lock": false
},
"attributes": {
"className": {
"type": "string",
"default": ""
},
"lock": {
"type": "object",
"default": {
"remove": true,
"move": true
}
}
},
"parent": [ "woocommerce/checkout" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,79 @@
/**
* External dependencies
*/
import classnames from 'classnames';
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 { useCheckoutBlockControlsContext } from '../../context';
import {
useForcedLayout,
getAllowedBlocks,
} from '../../../cart-checkout-shared';
import './style.scss';
export const Edit = ( {
clientId,
attributes,
}: {
clientId: string;
attributes: {
className?: string;
};
} ): JSX.Element => {
const blockProps = useBlockProps( {
className: classnames(
'wc-block-checkout__main',
attributes?.className
),
} );
const allowedBlocks = getAllowedBlocks( innerBlockAreas.CHECKOUT_FIELDS );
const { addressFieldControls: Controls } =
useCheckoutBlockControlsContext();
const defaultTemplate = [
[ 'woocommerce/checkout-express-payment-block', {}, [] ],
[ 'woocommerce/checkout-contact-information-block', {}, [] ],
[ 'woocommerce/checkout-shipping-address-block', {}, [] ],
[ 'woocommerce/checkout-billing-address-block', {}, [] ],
[ 'woocommerce/checkout-shipping-methods-block', {}, [] ],
[ 'woocommerce/checkout-payment-block', {}, [] ],
[ 'woocommerce/checkout-order-note-block', {}, [] ],
[ 'woocommerce/checkout-terms-block', {}, [] ],
[ 'woocommerce/checkout-actions-block', {}, [] ],
].filter( Boolean ) as unknown as TemplateArray;
useForcedLayout( {
clientId,
registeredBlocks: allowedBlocks,
defaultTemplate,
} );
return (
<Main { ...blockProps }>
<Controls />
<form className="wc-block-components-form wc-block-checkout__form">
<InnerBlocks
allowedBlocks={ allowedBlocks }
templateLock={ false }
template={ defaultTemplate }
renderAppender={ InnerBlocks.ButtonBlockAppender }
/>
</form>
</Main>
);
};
export const Save = (): JSX.Element => {
return (
<div { ...useBlockProps.save() }>
<InnerBlocks.Content />
</div>
);
};

View File

@@ -0,0 +1,28 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { Main } from '@woocommerce/base-components/sidebar-layout';
/**
* Internal dependencies
*/
import './style.scss';
const FrontendBlock = ( {
children,
className,
}: {
children: JSX.Element;
className?: string;
} ): JSX.Element => {
return (
<Main className={ classnames( 'wc-block-checkout__main', className ) }>
<form className="wc-block-components-form wc-block-checkout__form">
{ children }
</form>
</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,53 @@
.wc-block-checkout__form {
margin: 0;
max-width: 100%;
}
.is-mobile,
.is-small,
.is-medium {
.wc-block-checkout__main {
order: 1;
}
}
.is-small,
.is-medium,
.is-large {
.wc-block-checkout__shipping-fields,
.wc-block-checkout__billing-fields {
.wc-block-components-address-form {
margin-left: #{-$gap-small * 0.5};
margin-right: #{-$gap-small * 0.5};
&::after {
content: "";
clear: both;
display: block;
}
.wc-block-components-text-input,
.wc-block-components-country-input,
.wc-block-components-state-input {
float: left;
margin-left: #{$gap-small * 0.5};
margin-right: #{$gap-small * 0.5};
position: relative;
width: calc(50% - #{$gap-small});
&:nth-of-type(2),
&:first-of-type {
margin-top: 0;
}
}
.wc-block-components-address-form__company,
.wc-block-components-address-form__address_1,
.wc-block-components-address-form__address_2 {
width: calc(100% - #{$gap-small});
}
.wc-block-components-checkbox {
clear: both;
}
}
}
}

View File

@@ -0,0 +1,29 @@
{
"name": "woocommerce/checkout-order-note-block",
"version": "1.0.0",
"title": "Order Note",
"description": "Allow customers to add a note to their order.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false
},
"attributes": {
"className": {
"type": "string",
"default": ""
},
"lock": {
"type": "object",
"default": {
"remove": false,
"move": true
}
}
},
"parent": [ "woocommerce/checkout-fields-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,54 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { __ } from '@wordpress/i18n';
import { FormStep } from '@woocommerce/base-components/cart-checkout';
import { useCheckoutContext } from '@woocommerce/base-context';
import { useShippingData } from '@woocommerce/base-context/hooks';
/**
* Internal dependencies
*/
import CheckoutOrderNotes from '../../order-notes';
const Block = ( { className }: { className?: string } ): JSX.Element => {
const { needsShipping } = useShippingData();
const {
isProcessing: checkoutIsProcessing,
orderNotes,
dispatchActions,
} = useCheckoutContext();
const { setOrderNotes } = dispatchActions;
return (
<FormStep
id="order-notes"
showStepNumber={ false }
className={ classnames(
'wc-block-checkout__order-notes',
className
) }
disabled={ checkoutIsProcessing }
>
<CheckoutOrderNotes
disabled={ checkoutIsProcessing }
onChange={ setOrderNotes }
placeholder={
needsShipping
? __(
'Notes about your order, e.g. special notes for delivery.',
'woo-gutenberg-products-block'
)
: __(
'Notes about your order.',
'woo-gutenberg-products-block'
)
}
value={ orderNotes }
/>
</FormStep>
);
};
export default Block;

View File

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

View File

@@ -0,0 +1,12 @@
// Adjust padding and margins in the editor to improve selected block outlines.
.wp-block-woocommerce-checkout-order-note-block {
margin-top: 20px;
margin-bottom: 20px;
padding-top: 4px;
padding-bottom: 4px;
.wc-block-checkout__add-note {
margin-top: 0;
margin-bottom: 0;
}
}

View File

@@ -0,0 +1,24 @@
/**
* External dependencies
*/
import { Icon, page } 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={ page }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,13 @@
export default {
className: {
type: 'string',
default: '',
},
lock: {
type: 'object',
default: {
move: true,
remove: true,
},
},
};

View File

@@ -0,0 +1,25 @@
{
"name": "woocommerce/checkout-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
},
"attributes": {
"lock": {
"type": "object",
"default": {
"remove": true
}
}
},
"parent": [ "woocommerce/checkout-totals-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,66 @@
/**
* External dependencies
*/
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import type { TemplateArray } from '@wordpress/blocks';
import { innerBlockAreas } from '@woocommerce/blocks-checkout';
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.CHECKOUT_ORDER_SUMMARY
);
const defaultTemplate = [
[ 'woocommerce/checkout-order-summary-cart-items-block', {}, [] ],
[ 'woocommerce/checkout-order-summary-subtotal-block', {}, [] ],
[ 'woocommerce/checkout-order-summary-fee-block', {}, [] ],
[ 'woocommerce/checkout-order-summary-discount-block', {}, [] ],
[ 'woocommerce/checkout-order-summary-coupon-form-block', {}, [] ],
[ 'woocommerce/checkout-order-summary-shipping-block', {}, [] ],
[ 'woocommerce/checkout-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>
<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,27 @@
/**
* 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 attributes from './attributes';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ totals }
className="wc-block-editor-components-block-icon"
/>
),
},
attributes,
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,19 @@
/**
* External dependencies
*/
import { ExperimentalOrderMeta } from '@woocommerce/blocks-checkout';
import { useStoreCart } from '@woocommerce/base-context/hooks';
// @todo Consider deprecating OrderMetaSlotFill and DiscountSlotFill in favour of inner block areas.
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/checkout',
};
return <ExperimentalOrderMeta.Slot { ...slotFillProps } />;
};

View File

@@ -0,0 +1,503 @@
/**
* External dependencies
*/
import { render, findByText, queryByText } from '@testing-library/react';
/**
* Internal dependencies
*/
import { previewCart as mockPreviewCart } from '../../../../../previews/cart';
import {
textContentMatcher,
textContentMatcherAcrossSiblings,
} from '../../../../../../../tests/utils/find-by-text';
const baseContextHooks = jest.requireMock( '@woocommerce/base-context/hooks' );
const woocommerceSettings = jest.requireMock( '@woocommerce/settings' );
import SummaryBlock from '../frontend';
import SubtotalBlock from '../../checkout-order-summary-subtotal/frontend';
import FeeBlock from '../../checkout-order-summary-fee/frontend';
import TaxesBlock from '../../checkout-order-summary-taxes/frontend';
import DiscountBlock from '../../checkout-order-summary-discount/frontend';
import CouponsBlock from '../../checkout-order-summary-coupon-form/frontend';
import ShippingBlock from '../../checkout-order-summary-shipping/frontend';
import CartItemsBlock from '../../checkout-order-summary-cart-items/frontend';
const Block = ( { showRateAfterTaxName = false } ) => (
<SummaryBlock>
<CartItemsBlock />
<SubtotalBlock />
<FeeBlock />
<DiscountBlock />
<CouponsBlock />
<ShippingBlock />
<TaxesBlock showRateAfterTaxName={ showRateAfterTaxName } />
</SummaryBlock>
);
const defaultUseStoreCartValue = {
cartItems: mockPreviewCart.items,
cartTotals: mockPreviewCart.totals,
cartCoupons: mockPreviewCart.coupons,
cartFees: mockPreviewCart.fees,
cartNeedsShipping: mockPreviewCart.needs_shipping,
shippingRates: mockPreviewCart.shipping_rates,
shippingAddress: mockPreviewCart.shipping_address,
billingAddress: mockPreviewCart.billing_address,
cartHasCalculatedShipping: mockPreviewCart.has_calculated_shipping,
};
jest.mock( '@woocommerce/base-context/hooks', () => ( {
...jest.requireActual( '@woocommerce/base-context/hooks' ),
/*
We need to redefine this here despite the defaultUseStoreCartValue above
because jest doesn't like to set up mocks with out of scope variables
*/
useStoreCart: jest.fn().mockReturnValue( {
cartItems: mockPreviewCart.items,
cartTotals: mockPreviewCart.totals,
cartCoupons: mockPreviewCart.coupons,
cartFees: mockPreviewCart.fees,
cartNeedsShipping: mockPreviewCart.needs_shipping,
shippingRates: mockPreviewCart.shipping_rates,
shippingAddress: mockPreviewCart.shipping_address,
billingAddress: mockPreviewCart.billing_address,
cartHasCalculatedShipping: mockPreviewCart.has_calculated_shipping,
} ),
useShippingData: jest.fn().mockReturnValue( {
needsShipping: true,
shippingRates: [
{
package_id: 0,
name: 'Shipping method',
destination: {
address_1: '',
address_2: '',
city: '',
state: '',
postcode: '',
country: '',
},
items: [
{
key: 'fb0c0a746719a7596f296344b80cb2b6',
name: 'Hoodie - Blue, Yes',
quantity: 1,
},
{
key: '1f0e3dad99908345f7439f8ffabdffc4',
name: 'Beanie',
quantity: 1,
},
],
shipping_rates: [
{
rate_id: 'flat_rate:1',
name: 'Flat rate',
description: '',
delivery_time: '',
price: '500',
taxes: '0',
instance_id: 1,
method_id: 'flat_rate',
meta_data: [
{
key: 'Items',
value: 'Hoodie - Blue, Yes &times; 1, Beanie &times; 1',
},
],
selected: false,
currency_code: 'USD',
currency_symbol: '$',
currency_minor_unit: 2,
currency_decimal_separator: '.',
currency_thousand_separator: ',',
currency_prefix: '$',
currency_suffix: '',
},
{
rate_id: 'local_pickup:2',
name: 'Local pickup',
description: '',
delivery_time: '',
price: '0',
taxes: '0',
instance_id: 2,
method_id: 'local_pickup',
meta_data: [
{
key: 'Items',
value: 'Hoodie - Blue, Yes &times; 1, Beanie &times; 1',
},
],
selected: false,
currency_code: 'USD',
currency_symbol: '$',
currency_minor_unit: 2,
currency_decimal_separator: '.',
currency_thousand_separator: ',',
currency_prefix: '$',
currency_suffix: '',
},
{
rate_id: 'free_shipping:5',
name: 'Free shipping',
description: '',
delivery_time: '',
price: '0',
taxes: '0',
instance_id: 5,
method_id: 'free_shipping',
meta_data: [
{
key: 'Items',
value: 'Hoodie - Blue, Yes &times; 1, Beanie &times; 1',
},
],
selected: true,
currency_code: 'USD',
currency_symbol: '$',
currency_minor_unit: 2,
currency_decimal_separator: '.',
currency_thousand_separator: ',',
currency_prefix: '$',
currency_suffix: '',
},
],
},
],
} ),
} ) );
jest.mock( '@woocommerce/base-context', () => ( {
...jest.requireActual( '@woocommerce/base-context' ),
useContainerWidthContext: jest.fn().mockReturnValue( {
hasContainerWidth: true,
isLarge: true,
} ),
} ) );
jest.mock( '@woocommerce/settings', () => {
const originalModule = jest.requireActual( '@woocommerce/settings' );
return {
...originalModule,
getSetting: jest.fn().mockImplementation( ( setting, ...rest ) => {
if ( setting === 'couponsEnabled' ) {
return true;
}
return originalModule.getSetting( setting, ...rest );
} ),
};
} );
const setUseStoreCartReturnValue = ( value = defaultUseStoreCartValue ) => {
baseContextHooks.useStoreCart.mockReturnValue( value );
};
const setGetSettingImplementation = ( implementation ) => {
woocommerceSettings.getSetting.mockImplementation( implementation );
};
const setUseShippingDataReturnValue = ( value ) => {
baseContextHooks.useShippingData.mockReturnValue( value );
};
describe( 'Checkout Order Summary', () => {
beforeEach( () => {
setUseStoreCartReturnValue();
} );
it( 'Renders the standard preview items in the sidebar', async () => {
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
await findByText( container, 'Warm hat for winter' )
).toBeInTheDocument();
expect(
await findByText( container, 'Lightweight baseball cap' )
).toBeInTheDocument();
// Checking if variable product is rendered.
expect(
await findByText( container, textContentMatcher( 'Color: Yellow' ) )
).toBeInTheDocument();
expect(
await findByText( container, textContentMatcher( 'Size: Small' ) )
).toBeInTheDocument();
} );
it( 'Renders the items subtotal correctly', async () => {
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
await findByText(
container,
textContentMatcherAcrossSiblings( 'Subtotal $40.00' )
)
).toBeInTheDocument();
} );
// The cart_totals value of useStoreCart is what drives this
it( 'If discounted items are in the cart the discount subtotal is shown correctly', async () => {
setUseStoreCartReturnValue( {
...defaultUseStoreCartValue,
cartTotals: {
...mockPreviewCart.totals,
total_discount: 1000,
total_price: 3800,
},
} );
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
await findByText(
container,
textContentMatcherAcrossSiblings( 'Discount -$10.00' )
)
).toBeInTheDocument();
} );
it( 'If coupons are in the cart they are shown correctly', async () => {
setUseStoreCartReturnValue( {
...defaultUseStoreCartValue,
cartTotals: {
...mockPreviewCart.totals,
total_discount: 1000,
total_price: 3800,
},
cartCoupons: [
{
code: '10off',
discount_type: 'fixed_cart',
totals: {
total_discount: '1000',
total_discount_tax: '0',
currency_code: 'USD',
currency_symbol: '$',
currency_minor_unit: 2,
currency_decimal_separator: '.',
currency_thousand_separator: ',',
currency_prefix: '$',
currency_suffix: '',
},
label: '10off',
},
],
} );
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
await findByText( container, 'Coupon: 10off' )
).toBeInTheDocument();
} );
it( 'Shows fees if the cart_fees are set', async () => {
setUseStoreCartReturnValue( {
...defaultUseStoreCartValue,
cartFees: [
{
totals: {
currency_code: 'USD',
currency_decimal_separator: '.',
currency_minor_unit: 2,
currency_prefix: '$',
currency_suffix: '',
currency_symbol: '$',
currency_thousand_separator: ',',
total: 1000,
total_tax: '0',
},
},
],
} );
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
await findByText(
container,
textContentMatcherAcrossSiblings( 'Fee $10.00' )
)
).toBeInTheDocument();
} );
it( 'Shows the coupon entry form when coupons are enabled', async () => {
setUseStoreCartReturnValue();
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
await findByText( container, 'Coupon code' )
).toBeInTheDocument();
} );
it( 'Does not show the coupon entry if coupons are not enabled', () => {
setUseStoreCartReturnValue();
setGetSettingImplementation( ( setting, ...rest ) => {
if ( setting === 'couponsEnabled' ) {
return false;
}
const originalModule = jest.requireActual(
'@woocommerce/settings'
);
return originalModule.getSetting( setting, ...rest );
} );
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
queryByText( container, 'Coupon code' )
).not.toBeInTheDocument();
} );
it( 'Does not show the shipping section if needsShipping is false on the cart', () => {
setUseStoreCartReturnValue( {
...defaultUseStoreCartValue,
cartNeedsShipping: false,
} );
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect( queryByText( container, 'Shipping' ) ).not.toBeInTheDocument();
} );
it( 'Does not show the taxes section if displayCartPricesIncludingTax is true', () => {
setUseStoreCartReturnValue( {
...defaultUseStoreCartValue,
cartTotals: {
...mockPreviewCart.totals,
total_tax: '1000',
tax_lines: [ { name: 'Tax', price: '1000', rate: '5%' } ],
},
} );
setGetSettingImplementation( ( setting, ...rest ) => {
if ( setting === 'displayCartPricesIncludingTax' ) {
return true;
}
if ( setting === 'taxesEnabled' ) {
return true;
}
const originalModule = jest.requireActual(
'@woocommerce/settings'
);
return originalModule.getSetting( setting, ...rest );
} );
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
queryByText( container, 'Tax $10.00' )
).not.toBeInTheDocument();
} );
it( 'Shows the taxes section if displayCartPricesIncludingTax is false and a tax total is set', async () => {
setUseStoreCartReturnValue( {
...defaultUseStoreCartValue,
cartTotals: {
...mockPreviewCart.totals,
total_tax: '1000',
tax_lines: [ { name: 'Tax', price: '1000', rate: '5%' } ],
},
} );
setUseShippingDataReturnValue( { needsShipping: false } );
setGetSettingImplementation( ( setting, ...rest ) => {
if ( setting === 'displayCartPricesIncludingTax' ) {
return false;
}
if ( setting === 'taxesEnabled' ) {
return true;
}
const originalModule = jest.requireActual(
'@woocommerce/settings'
);
return originalModule.getSetting( setting, ...rest );
} );
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
await findByText(
container,
textContentMatcherAcrossSiblings( 'Taxes $10.00' )
)
).toBeInTheDocument();
} );
it( 'Shows the grand total correctly', async () => {
setUseStoreCartReturnValue( {
...defaultUseStoreCartValue,
cartTotals: {
...mockPreviewCart.totals,
},
cartNeedsShipping: false,
} );
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
await findByText(
container,
textContentMatcherAcrossSiblings( 'Total $49.20' )
)
).toBeInTheDocument();
} );
it( 'Correctly shows the shipping section if the cart requires shipping', async () => {
setUseStoreCartReturnValue( {
...defaultUseStoreCartValue,
cartTotals: {
...defaultUseStoreCartValue.cartTotals,
total_shipping: '4000',
},
cartNeedsShipping: true,
shippingRates: [
{
package_id: 0,
name: 'Shipping method',
destination: {
address_1: '',
address_2: '',
city: '',
state: '',
postcode: '',
country: '',
},
items: [
{
key: 'fb0c0a746719a7596f296344b80cb2b6',
name: 'Hoodie - Blue, Yes',
quantity: 1,
},
{
key: '1f0e3dad99908345f7439f8ffabdffc4',
name: 'Beanie',
quantity: 1,
},
],
shipping_rates: [
{
rate_id: 'free_shipping:5',
name: 'Free shipping',
description: '',
delivery_time: '',
price: '4000',
taxes: '0',
instance_id: 5,
method_id: 'free_shipping',
meta_data: [
{
key: 'Items',
value: 'Hoodie - Blue, Yes &times; 1, Beanie &times; 1',
},
],
selected: true,
currency_code: 'USD',
currency_symbol: '$',
currency_minor_unit: 2,
currency_decimal_separator: '.',
currency_thousand_separator: ',',
currency_prefix: '$',
currency_suffix: '',
},
],
},
],
} );
const { container } = render( <Block showRateAfterTaxName={ true } /> );
expect(
await findByText(
container,
textContentMatcherAcrossSiblings(
'Shipping $40.00 via Free shipping'
)
)
).toBeInTheDocument();
} );
} );

View File

@@ -0,0 +1,30 @@
{
"name": "woocommerce/checkout-order-summary-cart-items-block",
"version": "1.0.0",
"title": "Cart Items",
"description": "Shows cart items.",
"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/checkout-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,18 @@
/**
* External dependencies
*/
import { OrderSummary } from '@woocommerce/base-components/cart-checkout';
import { useStoreCart } from '@woocommerce/base-context/hooks';
import { TotalsWrapper } from '@woocommerce/blocks-checkout';
const Block = ( { className }: { className: string } ): JSX.Element => {
const { cartItems } = useStoreCart();
return (
<TotalsWrapper className={ className }>
<OrderSummary cartItems={ cartItems } />
</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 { cart } 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={ cart }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,29 @@
{
"name": "woocommerce/checkout-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/checkout-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,33 @@
/**
* 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/checkout' );
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/checkout-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/checkout-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,50 @@
/**
* 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/checkout',
};
return <ExperimentalDiscountsMeta.Slot { ...discountsSlotFillProps } />;
};
const Block = ( { className = '' }: { className?: string } ): JSX.Element => {
const { cartTotals, cartCoupons } = useStoreCart();
const { removeCoupon, isRemovingCoupon } =
useStoreCartCoupons( 'wc/checkout' );
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/checkout-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/checkout-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,26 @@
{
"name": "woocommerce/checkout-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/checkout-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,34 @@
/**
* 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 = '',
}: {
className?: string;
} ): JSX.Element | null => {
const { cartTotals, cartNeedsShipping } = useStoreCart();
if ( ! cartNeedsShipping ) {
return null;
}
const totalsCurrency = getCurrencyFromPriceResponse( cartTotals );
return (
<TotalsWrapper className={ className }>
<TotalsShipping
showCalculator={ false }
showRateSelector={ false }
values={ cartTotals }
currency={ totalsCurrency }
/>
</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;
};
} ): 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,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/checkout-order-summary-subtotal-block",
"version": "1.0.0",
"title": "Subtotal",
"description": "Shows the cart subtotal 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/checkout-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,19 @@
/**
* External dependencies
*/
import { Subtotal, 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 { cartTotals } = useStoreCart();
const totalsCurrency = getCurrencyFromPriceResponse( cartTotals );
return (
<TotalsWrapper className={ className }>
<Subtotal currency={ totalsCurrency } values={ cartTotals } />
</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 { getSetting } from '@woocommerce/settings';
export default {
showRateAfterTaxName: {
type: 'boolean',
default: getSetting( 'displayCartPricesIncludingTax', false ),
},
lock: {
type: 'object',
default: {
remove: true,
move: false,
},
},
};

View File

@@ -0,0 +1,30 @@
{
"name": "woocommerce/checkout-order-summary-taxes-block",
"version": "1.0.0",
"title": "Taxes",
"description": "Shows the cart taxes 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/checkout-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,42 @@
/**
* External dependencies
*/
import { TotalsTaxes, TotalsWrapper } from '@woocommerce/blocks-checkout';
import { getCurrencyFromPriceResponse } from '@woocommerce/price-format';
import { useStoreCart } from '@woocommerce/base-context/hooks';
import { getSetting } from '@woocommerce/settings';
const Block = ( {
className,
showRateAfterTaxName,
}: {
className: string;
showRateAfterTaxName: boolean;
} ): JSX.Element | null => {
const { cartTotals } = useStoreCart();
const displayCartPricesIncludingTax = getSetting(
'displayCartPricesIncludingTax',
false
);
if (
displayCartPricesIncludingTax ||
parseInt( cartTotals.total_tax, 10 ) <= 0
) {
return null;
}
const totalsCurrency = getCurrencyFromPriceResponse( cartTotals );
return (
<TotalsWrapper className={ className }>
<TotalsTaxes
showRateAfterTaxName={ showRateAfterTaxName }
currency={ totalsCurrency }
values={ cartTotals }
/>
</TotalsWrapper>
);
};
export default Block;

View File

@@ -0,0 +1,77 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, ToggleControl } from '@wordpress/components';
import { getSetting } from '@woocommerce/settings';
/**
* Internal dependencies
*/
import Block from './block';
export const Edit = ( {
attributes,
setAttributes,
}: {
attributes: {
className: string;
showRateAfterTaxName: boolean;
};
setAttributes: ( attributes: Record< string, unknown > ) => void;
} ): JSX.Element => {
const { className, showRateAfterTaxName } = attributes;
const blockProps = useBlockProps();
const taxesEnabled = getSetting( 'taxesEnabled' ) as boolean;
const displayItemizedTaxes = getSetting(
'displayItemizedTaxes',
false
) as boolean;
const displayCartPricesIncludingTax = getSetting(
'displayCartPricesIncludingTax',
false
) as boolean;
return (
<div { ...blockProps }>
<InspectorControls>
{ taxesEnabled &&
displayItemizedTaxes &&
! displayCartPricesIncludingTax && (
<PanelBody
title={ __(
'Taxes',
'woo-gutenberg-products-block'
) }
>
<ToggleControl
label={ __(
'Show rate after tax name',
'woo-gutenberg-products-block'
) }
help={ __(
'Show the percentage rate alongside each tax line in the summary.',
'woo-gutenberg-products-block'
) }
checked={ showRateAfterTaxName }
onChange={ () =>
setAttributes( {
showRateAfterTaxName:
! showRateAfterTaxName,
} )
}
/>
</PanelBody>
) }
</InspectorControls>
<Block
className={ className }
showRateAfterTaxName={ showRateAfterTaxName }
/>
</div>
);
};
export const Save = (): JSX.Element => {
return <div { ...useBlockProps.save() } />;
};

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,27 @@
/**
* 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 attributes from './attributes';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ totals }
className="wc-block-editor-components-block-icon"
/>
),
},
attributes,
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,27 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import formStepAttributes from '../../form-step/attributes';
export default {
...formStepAttributes( {
defaultTitle: __( 'Payment options', 'woo-gutenberg-products-block' ),
defaultDescription: '',
} ),
className: {
type: 'string',
default: '',
},
lock: {
type: 'object',
default: {
move: true,
remove: true,
},
},
};

View File

@@ -0,0 +1,27 @@
{
"name": "woocommerce/checkout-payment-block",
"version": "1.0.0",
"title": "Payment Options",
"description": "Payment options for your store.",
"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/checkout-fields-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,14 @@
/**
* External dependencies
*/
/**
* Internal dependencies
*/
import { PaymentMethods } from '../../../cart-checkout-shared/payment-methods';
const Block = (): JSX.Element | null => {
return <PaymentMethods />;
};
export default Block;

View File

@@ -0,0 +1,103 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { __ } from '@wordpress/i18n';
import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import { PanelBody, ExternalLink } from '@wordpress/components';
import { ADMIN_URL, getSetting } from '@woocommerce/settings';
import ExternalLinkCard from '@woocommerce/editor-components/external-link-card';
import { innerBlockAreas } from '@woocommerce/blocks-checkout';
import Noninteractive from '@woocommerce/base-components/noninteractive';
/**
* Internal dependencies
*/
import {
FormStepBlock,
AdditionalFields,
AdditionalFieldsContent,
} from '../../form-step';
import Block from './block';
type paymentAdminLink = {
id: number;
title: string;
description: string;
};
export const Edit = ( {
attributes,
setAttributes,
}: {
attributes: {
title: string;
description: string;
showStepNumber: boolean;
className: string;
};
setAttributes: ( attributes: Record< string, unknown > ) => void;
} ): JSX.Element => {
const globalPaymentMethods = getSetting(
'globalPaymentMethods'
) as paymentAdminLink[];
return (
<FormStepBlock
attributes={ attributes }
setAttributes={ setAttributes }
className={ classnames(
'wc-block-checkout__payment-method',
attributes?.className
) }
>
<InspectorControls>
{ globalPaymentMethods.length > 0 && (
<PanelBody
title={ __(
'Methods',
'woo-gutenberg-products-block'
) }
>
<p className="wc-block-checkout__controls-text">
{ __(
'You currently have the following payment integrations active.',
'woo-gutenberg-products-block'
) }
</p>
{ globalPaymentMethods.map( ( method ) => {
return (
<ExternalLinkCard
key={ method.id }
href={ `${ ADMIN_URL }admin.php?page=wc-settings&tab=checkout&section=${ method.id }` }
title={ method.title }
description={ method.description }
/>
);
} ) }
<ExternalLink
href={ `${ ADMIN_URL }admin.php?page=wc-settings&tab=checkout` }
>
{ __(
'Manage payment methods',
'woo-gutenberg-products-block'
) }
</ExternalLink>
</PanelBody>
) }
</InspectorControls>
<Noninteractive>
<Block />
</Noninteractive>
<AdditionalFields block={ innerBlockAreas.PAYMENT_METHODS } />
</FormStepBlock>
);
};
export const Save = (): JSX.Element => {
return (
<div { ...useBlockProps.save() }>
<AdditionalFieldsContent />
</div>
);
};

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