woocommerce/plugins/woocommerce-blocks/assets/js/blocks/cart/edit.js

197 lines
5.0 KiB
JavaScript
Raw Normal View History

/* tslint:disable */
/**
* External dependencies
*/
import classnames from 'classnames';
import { __ } from '@wordpress/i18n';
import { CartCheckoutFeedbackPrompt } from '@woocommerce/editor-components/feedback-prompt';
import {
useBlockProps,
InnerBlocks,
InspectorControls,
BlockControls,
} from '@wordpress/block-editor';
import { PanelBody, ToggleControl, Notice } from '@wordpress/components';
import { CartCheckoutCompatibilityNotice } from '@woocommerce/editor-components/compatibility-notices';
Move Block Type Settings into Block Type Classes (https://github.com/woocommerce/woocommerce-blocks/pull/4059) * BLOCK SETTINGS: Remove unused constants/settings * AssetDataRegistry: Helpers to check for settings that exist, and registering page ID/permalinks * Move checkout and cart block settings to checkout and cart blocktypes * Move isShippingCalculatorEnabled to cart block * Remove HAS_DARK_EDITOR_STYLE_SUPPORT and IS_SHIPPING_CALCULATOR_ENABLED in favour of getSetting * Move displayCartPricesIncludingTax to blocktypes, and implement getSetting * Move block settings to core settings and blocktypes * Fix namespace usage * Move review settings * move tag settings * Keep productCount in core data * Move min and default height * Improve storePages code * Move attributes to attribute filter block type * Move $word_count_type outside of settings array * Remove unneeded setting in preview data (shippingCostRequiresAddress) * Move min/max settings dependency from GridLayoutControl to Blocks themselves and use getSettings * DEFAULT_COLUMNS and ROWS to settings * Move product columns/rows to block types * Add grid settings to AllProducts block * Correct default rows * correct min rows default * Move hasDarkEditorStyleSupport * Move hideOutOfStockItems to block type settings * Move build settings to inline script dependency * Pass data through asset api and move restApiRoutes * Export all core settings as constants * Remove WORD_COUNT_TYPE from core settings * Move some other core settings to assets * Update constants * Make settings use TypeScript * Update CURRENT_USER_IS_ADMIN usage * WORD_COUNT_TYPE * REST_API_ROUTES * REVIEW_RATINGS_ENABLED and SHOW_AVATARS * Remove REVIEW_RATINGS_ENABLED and SHOW_AVATARS constants * Remove MIN_HEIGHT * Remove DEFAULT_HEIGHT * PLACEHOLDER_IMG_SRC * LIMIT_TAGS * HAS_PRODUCTS * HOME_URL * HAS_TAGS * COUPONS_ENABLED * SHIPPING_ENABLED * TAXES_ENABLED * DISPLAY_ITEMIZED_TAXES * SHIPPING_COST_REQUIRES_ADDRESS * SHIPPING_STATES and SHIPPING_COUNTRIES * STORE_PAGES * ALLOWED_COUNTRIES * ALLOWED_STATES * SHIPPING_METHODS_EXIST * PAYMENT_GATEWAY_SORT_ORDER * CHECKOUT_SHOW_LOGIN_REMINDER * CHECKOUT_ALLOWS_GUEST and CHECKOUT_ALLOWS_SIGNUP * ATTRIBUTES * DISPLAY_CART_PRICES_INCLUDING_TAX * DISPLAY_CART_PRICES_INCLUDING_TAX * update build for TS files * fix build dir * Move blocks build config params * Move placeholderImgSrc to core settings * Move rest api hydration hoc to shared hocs and provide it restApiRoutes directly to avoid asset data registration * Move wordCountType to abstract block * Remove WORD_COUNT_TYPE in favour of getSetting * Move IS_LARGE_CATALOG and PRODUCT_COUNT to abstract block type and use getSetting inline * Add wcBlocksConfig * fix tests * Remove unused $asset_data_registry * remove console.log * Move build settings to abstract block * Trigger build again * Move hydration back to regular hocs for compatibility with trunk (merge conflict) * Removed wcSharedHocsConfig * esc home url * Update search fixture * Update search snap * 40000 timeout * hasProducts -> productCount * Product Count is part of blocks config * update mocks * Use version comparison to determine if batching is enabled * Change isWpVersion * scrollTo button
2021-04-22 11:37:27 +00:00
import { CART_PAGE_ID } from '@woocommerce/block-settings';
import BlockErrorBoundary from '@woocommerce/base-components/block-error-boundary';
import {
EditorProvider,
useEditorContext,
CartProvider,
} from '@woocommerce/base-context';
import { createInterpolateElement } from '@wordpress/element';
import { getAdminLink } from '@woocommerce/settings';
import { previewCart } from '@woocommerce/resource-previews';
import { filledCart, removeCart } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
/**
* Internal dependencies
*/
WIP: Add Inner blocks to order summary (https://github.com/woocommerce/woocommerce-blocks/pull/6065) * Sub/Total/Fee inner blocks * Row blocks within the inner block * Update icons * Resolve stying issues * Remove old block * Pin totals row * Locking logic update * Heading inner block * Refactor where inner blocks are defined * Add todos * Todo for Consider deprecating OrderMetaSlotFill and DiscountSlotFill in favour of inner block areas. * Improve frontend registration of components using new entrypoint * Experiment- external block context * Revert "Experiment- external block context" This reverts commit 4b75668ec7eb62f065c6a488cd942a666e26204f. * Duplicate inner blocks to avoid conflicts with context * Remove todo * Rename block dir * Some test fixes * Fix import * fix import * linting * Remove unused attributes * Optional classname * fix coupons import * fix shipping mocks * Styling * Fix selectors in e2e tests * Add back the wc-block-components-totals-wrapper class that was used for each segment in the totals Order summary Because, removing them was: - a breaking change for the old structure - was making it harder to target the inner blocks. Before the class was used to target each segment - it was making the wc-block-components-totals-item behave as a child or parent depending on the inner block, inconsitency * Reuse the TotalsWrapper component for C& C blocks inner blocks This component was removed in this PR, but we wrap components in the Cart and Checkout sidebar in a TotalsWrapper. This will ensure consistent spacing and borders are applied to items in the sidebar. Co-authored-by: Nadir Seghir <nadir.seghir@gmail.com> Co-authored-by: Raluca Stan <ralucastn@gmail.com>
2022-04-01 13:45:18 +00:00
import './inner-blocks';
import './editor.scss';
import {
addClassToBody,
useViewSwitcher,
useBlockPropsWithLocking,
useForcedLayout,
WIP: Add Inner blocks to order summary (https://github.com/woocommerce/woocommerce-blocks/pull/6065) * Sub/Total/Fee inner blocks * Row blocks within the inner block * Update icons * Resolve stying issues * Remove old block * Pin totals row * Locking logic update * Heading inner block * Refactor where inner blocks are defined * Add todos * Todo for Consider deprecating OrderMetaSlotFill and DiscountSlotFill in favour of inner block areas. * Improve frontend registration of components using new entrypoint * Experiment- external block context * Revert "Experiment- external block context" This reverts commit 4b75668ec7eb62f065c6a488cd942a666e26204f. * Duplicate inner blocks to avoid conflicts with context * Remove todo * Rename block dir * Some test fixes * Fix import * fix import * linting * Remove unused attributes * Optional classname * fix coupons import * fix shipping mocks * Styling * Fix selectors in e2e tests * Add back the wc-block-components-totals-wrapper class that was used for each segment in the totals Order summary Because, removing them was: - a breaking change for the old structure - was making it harder to target the inner blocks. Before the class was used to target each segment - it was making the wc-block-components-totals-item behave as a child or parent depending on the inner block, inconsitency * Reuse the TotalsWrapper component for C& C blocks inner blocks This component was removed in this PR, but we wrap components in the Cart and Checkout sidebar in a TotalsWrapper. This will ensure consistent spacing and borders are applied to items in the sidebar. Co-authored-by: Nadir Seghir <nadir.seghir@gmail.com> Co-authored-by: Raluca Stan <ralucastn@gmail.com>
2022-04-01 13:45:18 +00:00
} from '../cart-checkout/shared';
import { CartBlockContext } from './context';
// This is adds a class to body to signal if the selected block is locked
addClassToBody();
// Array of allowed block names.
const ALLOWED_BLOCKS = [
'woocommerce/filled-cart-block',
'woocommerce/empty-cart-block',
];
const views = [
{
view: 'woocommerce/filled-cart-block',
label: __( 'Filled Cart', 'woo-gutenberg-products-block' ),
icon: <Icon icon={ filledCart } />,
},
{
view: 'woocommerce/empty-cart-block',
label: __( 'Empty Cart', 'woo-gutenberg-products-block' ),
icon: <Icon icon={ removeCart } />,
},
];
const BlockSettings = ( { attributes, setAttributes } ) => {
const { hasDarkControls } = attributes;
const { currentPostId } = useEditorContext();
return (
<InspectorControls>
{ currentPostId !== CART_PAGE_ID && (
<Notice
className="wc-block-cart__page-notice"
isDismissible={ false }
status="warning"
>
{ createInterpolateElement(
__(
'If you would like to use this block as your default cart you must update your <a>page settings in WooCommerce</a>.',
'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 = ( { className, attributes, setAttributes, clientId } ) => {
const { hasDarkControls } = attributes;
const { currentView, component: ViewSwitcherComponent } = useViewSwitcher(
clientId,
views
);
const defaultTemplate = [
[ 'woocommerce/filled-cart-block', {}, [] ],
[ 'woocommerce/empty-cart-block', {}, [] ],
];
const blockProps = useBlockPropsWithLocking( {
className: classnames( className, 'wp-block-woocommerce-cart', {
'is-editor-preview': attributes.isPreview,
} ),
} );
useForcedLayout( {
clientId,
registeredBlocks: ALLOWED_BLOCKS,
defaultTemplate,
} );
return (
<div { ...blockProps }>
<BlockErrorBoundary
header={ __(
'Cart Block Error',
'woo-gutenberg-products-block'
) }
text={ __(
'There was an error whilst rendering the cart block. If this problem continues, try re-creating the block.',
'woo-gutenberg-products-block'
) }
showErrorMessage={ true }
errorMessagePrefix={ __(
'Error message:',
'woo-gutenberg-products-block'
) }
>
<EditorProvider
currentView={ currentView }
previewData={ { previewCart } }
>
<BlockSettings
attributes={ attributes }
setAttributes={ setAttributes }
/>
<BlockControls __experimentalShareWithChildBlocks>
{ ViewSwitcherComponent }
</BlockControls>
<CartBlockContext.Provider
value={ {
hasDarkControls,
} }
>
<CartProvider>
<InnerBlocks
allowedBlocks={ ALLOWED_BLOCKS }
template={ defaultTemplate }
templateLock={ false }
/>
</CartProvider>
</CartBlockContext.Provider>
</EditorProvider>
</BlockErrorBoundary>
<CartCheckoutCompatibilityNotice blockName="cart" />
</div>
);
};
export const Save = () => {
return (
<div
{ ...useBlockProps.save( {
className: 'is-loading',
} ) }
>
<InnerBlocks.Content />
</div>
);
};