2020-04-08 15:03:39 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2020-07-14 19:46:44 +00:00
|
|
|
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
|
|
|
|
import { dispatch } from '@wordpress/data';
|
2020-04-08 15:03:39 +00:00
|
|
|
import { useStoreCart } from '@woocommerce/base-hooks';
|
2020-07-14 19:46:44 +00:00
|
|
|
import { useEffect, RawHTML } from '@wordpress/element';
|
2020-04-08 15:03:39 +00:00
|
|
|
import LoadingMask from '@woocommerce/base-components/loading-mask';
|
|
|
|
import {
|
|
|
|
ValidationContextProvider,
|
|
|
|
CartProvider,
|
|
|
|
} from '@woocommerce/base-context';
|
2020-07-14 19:46:44 +00:00
|
|
|
import { translateJQueryEventToNative } from '@woocommerce/base-utils';
|
|
|
|
import withScrollToTop from '@woocommerce/base-hocs/with-scroll-to-top';
|
2020-04-08 15:03:39 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import FullCart from './full-cart';
|
|
|
|
|
2020-07-14 19:46:44 +00:00
|
|
|
const Block = ( { emptyCart, attributes, scrollToTop } ) => {
|
2020-04-08 15:03:39 +00:00
|
|
|
const { cartItems, cartIsLoading } = useStoreCart();
|
|
|
|
|
2020-07-14 19:46:44 +00:00
|
|
|
useEffect( () => {
|
|
|
|
const invalidateCartData = () => {
|
|
|
|
dispatch( storeKey ).invalidateResolutionForStore();
|
|
|
|
scrollToTop();
|
|
|
|
};
|
|
|
|
|
|
|
|
// Make it so we can read jQuery events triggered by WC Core elements.
|
|
|
|
const removeJQueryAddedToCartEvent = translateJQueryEventToNative(
|
|
|
|
'added_to_cart',
|
|
|
|
'wc-blocks_added_to_cart'
|
|
|
|
);
|
|
|
|
const removeJQueryRemovedFromCartEvent = translateJQueryEventToNative(
|
|
|
|
'removed_from_cart',
|
|
|
|
'wc-blocks_removed_from_cart'
|
|
|
|
);
|
|
|
|
|
|
|
|
document.body.addEventListener(
|
|
|
|
'wc-blocks_added_to_cart',
|
|
|
|
invalidateCartData
|
|
|
|
);
|
|
|
|
document.body.addEventListener(
|
|
|
|
'wc-blocks_removed_from_cart',
|
|
|
|
invalidateCartData
|
|
|
|
);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
removeJQueryAddedToCartEvent();
|
|
|
|
removeJQueryRemovedFromCartEvent();
|
|
|
|
|
|
|
|
document.body.removeEventListener(
|
|
|
|
'wc-blocks_added_to_cart',
|
|
|
|
invalidateCartData
|
|
|
|
);
|
|
|
|
document.body.removeEventListener(
|
|
|
|
'wc-blocks_removed_from_cart',
|
|
|
|
invalidateCartData
|
|
|
|
);
|
|
|
|
};
|
|
|
|
}, [ scrollToTop ] );
|
|
|
|
|
2020-04-08 15:03:39 +00:00
|
|
|
return (
|
|
|
|
<>
|
|
|
|
{ ! cartIsLoading && cartItems.length === 0 ? (
|
|
|
|
<RawHTML>{ emptyCart }</RawHTML>
|
|
|
|
) : (
|
|
|
|
<LoadingMask showSpinner={ true } isLoading={ cartIsLoading }>
|
|
|
|
<ValidationContextProvider>
|
|
|
|
<CartProvider>
|
|
|
|
<FullCart attributes={ attributes } />
|
|
|
|
</CartProvider>
|
|
|
|
</ValidationContextProvider>
|
|
|
|
</LoadingMask>
|
|
|
|
) }
|
|
|
|
</>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
2020-07-14 19:46:44 +00:00
|
|
|
export default withScrollToTop( Block );
|