Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Interactivity API and Product Button (#10006)
Browse files Browse the repository at this point in the history
* Update Interactivity API JS files

* Disable TS checks in the Interactivity API for now

* Add new SSR files

* Replace wp_ prefixes with wc_ ones

* Replace wp- prefix with wc-

* Replace guternberg_ prefix with woocommerce_

* Remove file comments from Gutenberg

* Rename files with `wp` prefix

* Fix code to load Interactivity API php files

* Remove TODO comments

* Replace @WordPress with @woocommerce

* Update Webpack configuration

* Fix directive prefix

* Remove interactivity folder from tsconfig exclude

* Add client-side navigation meta tag code

* Remove unneeded blocks.php file

* Fix store tag id

* Register Interactivity API runtime script

* Fix Interactivity API runtime registering

* Remove all files related to directive processing in PHP

* Move json_encode to Store's render method

* WIP

* WIP

* WIP

* WIP

* Preserve previous context

* Ignore Minicart block on client-side navigation

* Refresh page on store updatRefresh page on store updatee

* Refactor logic

* Add console error when a path is missing

* fix PHP lint error

* WIP store

* use store approach

* update jest configuration

* restore Mini Cart changes

* move cart store subscription to interactivity package

* move interactivity flag

* format HTML

* move addToCartText to the context

* Load product-query stylesheet when rendering the Products block

* update sideEffects array

* fix catch

* rename moreThanOneItem to isThereMoreThanOneItem

* improve how scripts are enqueued

* update default value for the filter woocommerce_blocks_enable_interactivity_api

* Update assets/js/atomic/blocks/product-elements/button/block.json

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

* Update assets/js/interactivity/cart/cart-store.ts

Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>

* fix block.json

* remove updateStore function

* restore interactivity api changes

* import cart store

* show notice when there is an error

* add logic to dequeue script on classic themes and block themes

* imrpove logic about notice

* Interactivity API: add `afterLoad` callbacks to `store()` function (#10338)

* show notice when there is an error

* Add initial implementation for store callbacks

* Run `afterLoad` callbacks after `init`

* Move cart state subscription to Product button

* Remove cart-store from Interactivity API internals

* Change callbacks with options and save only afterLoad callbacks

* ProductButton: Add animation (#10351)

* implement animation

* improve logic

* refactor logic

* refactor code

* address feedback about code style

* add support for woocommerce_add_to_cart_quantity

* Fix animation flickering

* Introduce wp-effect, reduce the amount of numberOfItem variables to 2 and consolidate animation status

* add support for added class

* Remove unnecessary selector

* Don't fetch cart if it was already fetched

* remove added class

---------

Co-authored-by: Luis Herranz <luisherranz@gmail.com>

---------

Co-authored-by: Luigi <gigitux@gmail.com>
Co-authored-by: Luis Herranz <luisherranz@gmail.com>

* update deepsignal

* remove added class

* update deepsignal

* Interactivity API and Product Button: Add E2E tests (#10036)

* Add FrontendUtils class

* fix conflicts

* use locator

* restore click usage

* Product Button: Add E2E test

* fix util

* fix E2E tests

* remove comment

* Add E2E test to ensure that woocommerce_product_add_to_cart_text works

* update sideEffects array

* add zip and unzip as package

* fix wp-env configuration

* fix E2E test

* add report

* try now

* try now

* try now

* fix E2E test

* E2E: Add documentation for testing actions and filters. Fixes #10135 (#10206)

* update description

* fix label

* rename files

* make requestUtils private

* remove page.goto

* use toHaveCount

* use productsToDisplay variable

* fix E2E tests

* rename class utils

---------

Co-authored-by: Daniel Dudzic <daniel.dudzic@automattic.com>

---------

Co-authored-by: David Arenas <david.arenas@automattic.com>
Co-authored-by: Luis Herranz <luisherranz@gmail.com>
Co-authored-by: Albert Juhé Lluveras <contact@albertjuhe.com>
Co-authored-by: Daniel Dudzic <daniel.dudzic@automattic.com>
  • Loading branch information
5 people authored Aug 10, 2023
1 parent 5c99f33 commit 16aef90
Show file tree
Hide file tree
Showing 29 changed files with 906 additions and 46 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ module.exports = {
'@wordpress/url',
'@woocommerce/blocks-test-utils',
'@woocommerce/e2e-utils',
'@woocommerce/e2e-mocks',
'babel-jest',
'dotenv',
'jest-environment-puppeteer',
Expand Down
3 changes: 2 additions & 1 deletion .wp-env.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"wp-content/plugins/gutenberg-test-plugins": "./node_modules/@wordpress/e2e-tests/plugins",
"wp-content/plugins/woocommerce-blocks": ".",
"wp-content/plugins/woocommerce-gutenberg-products-block": ".",
"wp-cli.yml": "./wp-cli.yml"
"wp-cli.yml": "./wp-cli.yml",
"custom-plugins" : "./tests/e2e/mocks/custom-plugins"
}
}
},
Expand Down
4 changes: 4 additions & 0 deletions assets/js/atomic/blocks/product-elements/button/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"background": false,
"link": true
},
"interactivity": true,
"html": false,
"typography": {
"fontSize": true,
Expand All @@ -57,6 +58,9 @@
"label": "Outline"
}
],
"viewScript": [
"wc-product-button-interactivity-frontend"
],
"apiVersion": 2,
"$schema": "https://schemas.wp.org/trunk/block.json"
}
279 changes: 279 additions & 0 deletions assets/js/atomic/blocks/product-elements/button/frontend.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,279 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* External dependencies
*/
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
import { store as interactivityStore } from '@woocommerce/interactivity';
import { dispatch, select, subscribe } from '@wordpress/data';
import { Cart } from '@woocommerce/type-defs/cart';
import { createRoot } from '@wordpress/element';
import NoticeBanner from '@woocommerce/base-components/notice-banner';

type Context = {
woocommerce: {
isLoading: boolean;
addToCartText: string;
productId: number;
displayViewCart: boolean;
quantityToAdd: number;
temporaryNumberOfItems: number;
animationStatus: AnimationStatus;
};
};

enum AnimationStatus {
IDLE = 'IDLE',
SLIDE_OUT = 'SLIDE-OUT',
SLIDE_IN = 'SLIDE-IN',
}

type State = {
woocommerce: {
cart: Cart | undefined;
inTheCartText: string;
};
};

type Store = {
state: State;
context: Context;
selectors: any;
ref: HTMLElement;
};

const storeNoticeClass = '.wc-block-store-notices';

const createNoticeContainer = () => {
const noticeContainer = document.createElement( 'div' );
noticeContainer.classList.add( storeNoticeClass.replace( '.', '' ) );
return noticeContainer;
};

const injectNotice = ( domNode: Element, errorMessage: string ) => {
const root = createRoot( domNode );

root.render(
<NoticeBanner status="error" onRemove={ () => root.unmount() }>
{ errorMessage }
</NoticeBanner>
);

domNode?.scrollIntoView( {
behavior: 'smooth',
inline: 'nearest',
} );
};

const getProductById = ( cartState: Cart | undefined, productId: number ) => {
return cartState?.items.find( ( item ) => item.id === productId );
};

const getTextButton = ( {
addToCartText,
inTheCartText,
numberOfItems,
}: {
addToCartText: string;
inTheCartText: string;
numberOfItems: number;
} ) => {
if ( numberOfItems === 0 ) {
return addToCartText;
}
return inTheCartText.replace( '###', numberOfItems.toString() );
};

const productButtonSelectors = {
woocommerce: {
addToCartText: ( store: Store ) => {
const { context, state, selectors } = store;

// We use the temporary number of items when there's no animation, or the
// second part of the animation hasn't started.
if (
context.woocommerce.animationStatus === AnimationStatus.IDLE ||
context.woocommerce.animationStatus ===
AnimationStatus.SLIDE_OUT
) {
return getTextButton( {
addToCartText: context.woocommerce.addToCartText,
inTheCartText: state.woocommerce.inTheCartText,
numberOfItems: context.woocommerce.temporaryNumberOfItems,
} );
}

return getTextButton( {
addToCartText: context.woocommerce.addToCartText,
inTheCartText: state.woocommerce.inTheCartText,
numberOfItems:
selectors.woocommerce.numberOfItemsInTheCart( store ),
} );
},
displayViewCart: ( store: Store ) => {
const { context, selectors } = store;
if ( ! context.woocommerce.displayViewCart ) return false;
if ( ! selectors.woocommerce.hasCartLoaded( store ) ) {
return context.woocommerce.temporaryNumberOfItems > 0;
}
return selectors.woocommerce.numberOfItemsInTheCart( store ) > 0;
},
hasCartLoaded: ( { state }: { state: State } ) => {
return state.woocommerce.cart !== undefined;
},
numberOfItemsInTheCart: ( { state, context }: Store ) => {
const product = getProductById(
state.woocommerce.cart,
context.woocommerce.productId
);
return product?.quantity || 0;
},
slideOutAnimation: ( { context }: Store ) =>
context.woocommerce.animationStatus === AnimationStatus.SLIDE_OUT,
slideInAnimation: ( { context }: Store ) =>
context.woocommerce.animationStatus === AnimationStatus.SLIDE_IN,
},
};

interactivityStore(
// @ts-expect-error: Store function isn't typed.
{
selectors: productButtonSelectors,
actions: {
woocommerce: {
addToCart: async ( store: Store ) => {
const { context, selectors, ref } = store;

if ( ! ref.classList.contains( 'ajax_add_to_cart' ) ) {
return;
}

context.woocommerce.isLoading = true;

// Allow 3rd parties to validate and quit early.
// https://github.com/woocommerce/woocommerce/blob/154dd236499d8a440edf3cde712511b56baa8e45/plugins/woocommerce/client/legacy/js/frontend/add-to-cart.js/#L74-L77
const event = new CustomEvent(
'should_send_ajax_request.adding_to_cart',
{ detail: [ ref ], cancelable: true }
);
const shouldSendRequest =
document.body.dispatchEvent( event );

if ( shouldSendRequest === false ) {
const ajaxNotSentEvent = new CustomEvent(
'ajax_request_not_sent.adding_to_cart',
{ detail: [ false, false, ref ] }
);
document.body.dispatchEvent( ajaxNotSentEvent );
return true;
}

try {
await dispatch( storeKey ).addItemToCart(
context.woocommerce.productId,
context.woocommerce.quantityToAdd
);

// After the cart has been updated, sync the temporary number of
// items again.
context.woocommerce.temporaryNumberOfItems =
selectors.woocommerce.numberOfItemsInTheCart(
store
);
} catch ( error ) {
const storeNoticeBlock =
document.querySelector( storeNoticeClass );

if ( ! storeNoticeBlock ) {
document
.querySelector( '.entry-content' )
?.prepend( createNoticeContainer() );
}

const domNode =
storeNoticeBlock ??
document.querySelector( storeNoticeClass );

if ( domNode ) {
injectNotice( domNode, error.message );
}

// We don't care about errors blocking execution, but will
// console.error for troubleshooting.
// eslint-disable-next-line no-console
console.error( error );
} finally {
context.woocommerce.displayViewCart = true;
context.woocommerce.isLoading = false;
}
},
handleAnimationEnd: (
store: Store & { event: AnimationEvent }
) => {
const { event, context, selectors } = store;
if ( event.animationName === 'slideOut' ) {
// When the first part of the animation (slide-out) ends, we move
// to the second part (slide-in).
context.woocommerce.animationStatus =
AnimationStatus.SLIDE_IN;
} else if ( event.animationName === 'slideIn' ) {
// When the second part of the animation ends, we update the
// temporary number of items to sync it with the cart and reset the
// animation status so it can be triggered again.
context.woocommerce.temporaryNumberOfItems =
selectors.woocommerce.numberOfItemsInTheCart(
store
);
context.woocommerce.animationStatus =
AnimationStatus.IDLE;
}
},
},
},
effects: {
woocommerce: {
startAnimation: ( store: Store ) => {
const { context, selectors } = store;
// We start the animation if the cart has loaded, the temporary number
// of items is out of sync with the number of items in the cart, the
// button is not loading (because that means the user started the
// interaction) and the animation hasn't started yet.
if (
selectors.woocommerce.hasCartLoaded( store ) &&
context.woocommerce.temporaryNumberOfItems !==
selectors.woocommerce.numberOfItemsInTheCart(
store
) &&
! context.woocommerce.isLoading &&
context.woocommerce.animationStatus ===
AnimationStatus.IDLE
) {
context.woocommerce.animationStatus =
AnimationStatus.SLIDE_OUT;
}
},
},
},
},
{
afterLoad: ( store: Store ) => {
const { state, selectors } = store;
// Subscribe to changes in Cart data.
subscribe( () => {
const cartData = select( storeKey ).getCartData();
const isResolutionFinished =
select( storeKey ).hasFinishedResolution( 'getCartData' );
if ( isResolutionFinished ) {
state.woocommerce.cart = cartData;
}
}, storeKey );

// This selector triggers a fetch of the Cart data. It is done in a
// `requestIdleCallback` to avoid potential performance issues.
requestIdleCallback( () => {
if ( ! selectors.woocommerce.hasCartLoaded( store ) ) {
select( storeKey ).getCartData();
}
} );
},
}
);
67 changes: 65 additions & 2 deletions assets/js/atomic/blocks/product-elements/button/style.scss
Original file line number Diff line number Diff line change
@@ -1,15 +1,78 @@
.wp-block-button.wc-block-components-product-button {
word-break: break-word;
white-space: normal;
display: flex;
justify-content: center;
align-items: center;
gap: $gap-small;

.wp-block-button__link {
word-break: break-word;
white-space: normal;
display: inline-flex;
justify-content: center;
text-align: center;
// Set button font size and padding so it inherits from parent.
padding: 0.5em 1em;
font-size: 1em;

&.loading {
opacity: 0.25;
}

&.loading::after {
font-family: WooCommerce; /* stylelint-disable-line */
content: "\e031";
animation: spin 2s linear infinite;
margin-left: 0.5em;
display: inline-block;
width: auto;
height: auto;
}
}

a[hidden] {
display: none;
}

@keyframes slideOut {
from {
transform: translateY(0);
}
to {
transform: translateY(-100%);
}
}

@keyframes slideIn {
from {
transform: translateY(90%);
opacity: 0;
}
to {
transform: translate(0);
opacity: 1;
}
}

.wc-block-components-product-button__button {
border-style: none;
display: inline-flex;
justify-content: center;
margin-right: auto;
margin-left: auto;
white-space: normal;
word-break: break-word;
width: 150px;
overflow: hidden;

span {

&.wc-block-slide-out {
animation: slideOut 0.1s linear 1 normal forwards;
}
&.wc-block-slide-in {
animation: slideIn 0.1s linear 1 normal;
}
}
}

.wc-block-components-product-button__button--placeholder {
Expand Down
Loading

0 comments on commit 16aef90

Please sign in to comment.