Commit 9472497b66b for woocommerce
commit 9472497b66bea840552bab2496461b20f50b0c5e
Author: Chris Lilitsas <1105590+xristos3490@users.noreply.github.com>
Date: Fri Nov 27 10:38:44 2026 +0200
Integrate the Back in Stock form with the Add to Cart + Options block (#71047)
* fix: Show the Back in Stock form with the Add to Cart + Options block
* fix: resolve PHPStan errors in the Back in Stock block integration
* refactor: read Add to Cart + Options context for Back in Stock attributes
* fix: import SelectedAttributes from the reorganized woocommerce store
* fix: match the Back in Stock email input and button heights
* fix: offer parent sign-ups when no variation of a block product can be bought
* test: drop redundant not-nested check from the BIS block e2e test
* test: look up attribute IDs with getProductAttributeIds in BIS e2e test
* test: drop redundant form ID assertion in the BIS block PHP test
* test: check BIS form visibility with the HTML tag processor, not a regex
* test: check the posted BIS form fields instead of querying the DB
diff --git a/plugins/woocommerce/changelog/fix-70182-bis-add-to-cart-with-options b/plugins/woocommerce/changelog/fix-70182-bis-add-to-cart-with-options
new file mode 100644
index 00000000000..8e4fffc6863
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-70182-bis-add-to-cart-with-options
@@ -0,0 +1,4 @@
+Significance: minor
+Type: fix
+
+Show the Back in Stock sign-up form with the Add to Cart + Options block, including for out-of-stock variations.
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/add-to-cart-with-options/back-in-stock-form/frontend.ts b/plugins/woocommerce/client/blocks/assets/js/blocks/add-to-cart-with-options/back-in-stock-form/frontend.ts
new file mode 100644
index 00000000000..56e5d8d3f84
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/add-to-cart-with-options/back-in-stock-form/frontend.ts
@@ -0,0 +1,71 @@
+/**
+ * External dependencies
+ */
+import { store, getContext } from '@wordpress/interactivity';
+import type { SelectedAttributes } from '@woocommerce/stores/woocommerce';
+import '@woocommerce/stores/woocommerce/products';
+import type { ProductsStore } from '@woocommerce/stores/woocommerce/products';
+
+/**
+ * Internal dependencies
+ */
+import { attributeNamesMatch } from '../../../base/utils/variations/attribute-matching';
+
+// Stores are locked to prevent 3PD usage until the API is stable.
+const universalLock =
+ 'I acknowledge that using a private store means my plugin will inevitably break on the next store release.';
+
+const { state: productsState } = store< ProductsStore >(
+ 'woocommerce/products',
+ {},
+ { lock: universalLock }
+);
+
+export type BackInStockFormStore = {
+ state: {
+ isVisible: boolean;
+ selectedAttributeValue: string;
+ };
+};
+
+/**
+ * Drives the Back in Stock form rendered after the Add to Cart + Options block
+ * of a variable product, see templates/single-product/back-in-stock-form.php.
+ */
+store< BackInStockFormStore >(
+ 'woocommerce/back-in-stock-form',
+ {
+ state: {
+ /**
+ * Whether the selected variation can't be bought, so shoppers
+ * can sign up for it.
+ */
+ get isVisible(): boolean {
+ const variation = productsState.productVariationInContext;
+
+ return (
+ !! variation &&
+ ! ( variation.is_in_stock && variation.is_purchasable )
+ );
+ },
+ /**
+ * Selected value of the attribute in context, read from the
+ * Add to Cart + Options block the input renders in.
+ */
+ get selectedAttributeValue(): string {
+ const { attribute } = getContext< { attribute: string } >();
+ const { selectedAttributes = [] } =
+ getContext< { selectedAttributes?: SelectedAttributes[] } >(
+ 'woocommerce/add-to-cart-with-options'
+ ) ?? {};
+
+ return (
+ selectedAttributes.find( ( selected ) =>
+ attributeNamesMatch( selected.attribute, attribute )
+ )?.value ?? ''
+ );
+ },
+ },
+ },
+ { lock: universalLock }
+);
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/add-to-cart-with-options/back-in-stock-form/test/frontend.ts b/plugins/woocommerce/client/blocks/assets/js/blocks/add-to-cart-with-options/back-in-stock-form/test/frontend.ts
new file mode 100644
index 00000000000..20a06ea7b17
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/add-to-cart-with-options/back-in-stock-form/test/frontend.ts
@@ -0,0 +1,91 @@
+/**
+ * External dependencies
+ */
+import type { SelectedAttributes } from '@woocommerce/stores/woocommerce';
+
+/**
+ * Internal dependencies
+ */
+import type { BackInStockFormStore } from '../frontend';
+
+type BlockContext = { selectedAttributes?: SelectedAttributes[] };
+
+let mockBlockContext: BlockContext | undefined;
+let mockRegisteredStore: BackInStockFormStore;
+
+const mockProductsState = {
+ productVariationInContext: null as Record< string, unknown > | null,
+};
+
+jest.mock(
+ '@wordpress/interactivity',
+ () => ( {
+ store: jest.fn( ( namespace, definition ) => {
+ if ( namespace === 'woocommerce/products' ) {
+ return { state: mockProductsState };
+ }
+ mockRegisteredStore = definition;
+ return definition;
+ } ),
+ getContext: jest.fn( ( namespace?: string ) =>
+ namespace === 'woocommerce/add-to-cart-with-options'
+ ? mockBlockContext
+ : { attribute: 'Size' }
+ ),
+ } ),
+ { virtual: true }
+);
+
+jest.mock( '@woocommerce/stores/woocommerce/products', () => ( {} ) );
+
+describe( 'Back in Stock form store', () => {
+ beforeEach( () => {
+ jest.resetModules();
+ mockBlockContext = undefined;
+ mockProductsState.productVariationInContext = null;
+
+ return import( '../frontend' );
+ } );
+
+ it.each( [
+ { variation: null, expected: false },
+ {
+ variation: { is_in_stock: true, is_purchasable: true },
+ expected: false,
+ },
+ {
+ variation: { is_in_stock: false, is_purchasable: true },
+ expected: true,
+ },
+ {
+ variation: { is_in_stock: true, is_purchasable: false },
+ expected: true,
+ },
+ ] )(
+ 'is visible ($expected) for variation $variation',
+ ( { variation, expected } ) => {
+ mockProductsState.productVariationInContext = variation;
+
+ expect( mockRegisteredStore.state.isVisible ).toBe( expected );
+ }
+ );
+
+ it( 'reads the selected attribute value from the Add to Cart + Options context', () => {
+ expect( mockRegisteredStore.state.selectedAttributeValue ).toBe( '' );
+
+ mockBlockContext = {
+ selectedAttributes: [
+ { attribute: 'Color', value: 'blue' },
+ { attribute: 'size', value: 'large' },
+ ],
+ };
+
+ expect( mockRegisteredStore.state.selectedAttributeValue ).toBe(
+ 'large'
+ );
+
+ mockBlockContext = {};
+
+ expect( mockRegisteredStore.state.selectedAttributeValue ).toBe( '' );
+ } );
+} );
diff --git a/plugins/woocommerce/client/blocks/bin/webpack-config-interactive-blocks.js b/plugins/woocommerce/client/blocks/bin/webpack-config-interactive-blocks.js
index 2f25a91db42..98456e5c798 100644
--- a/plugins/woocommerce/client/blocks/bin/webpack-config-interactive-blocks.js
+++ b/plugins/woocommerce/client/blocks/bin/webpack-config-interactive-blocks.js
@@ -55,6 +55,10 @@ const entries = {
// (cross-sells, upsells). Conditionally enqueued.
'woocommerce/product-collection-cart-reference':
'./assets/js/blocks/product-collection/cart-reference-frontend.ts',
+ // Back in Stock form frontend module. Enqueued when the form is rendered
+ // after the Add to Cart + Options block of a variable product.
+ 'woocommerce/back-in-stock-form':
+ './assets/js/blocks/add-to-cart-with-options/back-in-stock-form/frontend.ts',
// Other
'@woocommerce/stores/woocommerce':
'./assets/js/base/stores/woocommerce/index.ts',
diff --git a/plugins/woocommerce/client/legacy/css/woocommerce.scss b/plugins/woocommerce/client/legacy/css/woocommerce.scss
index 2fdedc46972..81ba790009d 100644
--- a/plugins/woocommerce/client/legacy/css/woocommerce.scss
+++ b/plugins/woocommerce/client/legacy/css/woocommerce.scss
@@ -1333,7 +1333,7 @@ p.demo_store,
display: flex;
flex-wrap: wrap;
flex-direction: row;
- align-items: center;
+ align-items: stretch;
justify-content: flex-start;
gap: 0.7em;
margin: 0.7em 0;
diff --git a/plugins/woocommerce/src/Internal/StockNotifications/Frontend/ProductPageIntegration.php b/plugins/woocommerce/src/Internal/StockNotifications/Frontend/ProductPageIntegration.php
index 71bdc75203a..3b27da612ec 100644
--- a/plugins/woocommerce/src/Internal/StockNotifications/Frontend/ProductPageIntegration.php
+++ b/plugins/woocommerce/src/Internal/StockNotifications/Frontend/ProductPageIntegration.php
@@ -4,6 +4,7 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Internal\StockNotifications\Frontend;
+use Automattic\WooCommerce\Blocks\BlockTypes\AddToCartWithOptions\Utils as AddToCartWithOptionsUtils;
use Automattic\WooCommerce\Internal\StockNotifications\Config;
use Automattic\WooCommerce\Internal\StockNotifications\Utilities\EligibilityService;
use Automattic\WooCommerce\Internal\StockNotifications\Frontend\MyAccountEndpoint;
@@ -21,6 +22,11 @@ class ProductPageIntegration {
*/
private const ADD_TO_CART_WITH_OPTIONS_BLOCK = 'woocommerce/add-to-cart-with-options';
+ /**
+ * Script module that shows the form for the variation chosen in the Add to Cart + Options block.
+ */
+ private const SCRIPT_MODULE = 'woocommerce/back-in-stock-form';
+
/**
* Runtime cache for preventing double rendering.
*
@@ -61,6 +67,7 @@ class ProductPageIntegration {
public function __construct() {
add_action( 'woocommerce_simple_add_to_cart', array( $this, 'maybe_render_form' ), 30 );
add_action( 'woocommerce_after_add_to_cart_form', array( $this, 'maybe_render_form' ), 30 );
+ add_filter( 'render_block_' . self::ADD_TO_CART_WITH_OPTIONS_BLOCK, array( $this, 'render_form_after_add_to_cart_with_options' ), 10, 3 );
}
/**
@@ -70,19 +77,122 @@ class ProductPageIntegration {
*/
public function maybe_render_form() {
- if ( ! Config::allows_signups() ) {
- return;
- }
-
// Add to Cart + Options buffers this hook inside its <form> and falls back to a
- // legacy HTML form when the buffer contains form elements. Block-theme support
- // will ship separately.
+ // legacy HTML form when the buffer contains form elements. The form is appended
+ // after the block instead, see render_form_after_add_to_cart_with_options().
if ( $this->is_rendering_inside_add_to_cart_with_options() ) {
return;
}
global $product;
- if ( ! is_product() || ! is_a( $product, 'WC_Product' ) ) {
+ if ( is_a( $product, 'WC_Product' ) ) {
+ $this->maybe_render_product_form( $product );
+ }
+ }
+
+ /**
+ * Append the BIS form to the Add to Cart + Options block, outside its <form>.
+ *
+ * @internal
+ *
+ * @param string $block_content The block content.
+ * @param array $parsed_block The parsed block.
+ * @param \WP_Block $block The block instance.
+ * @return string
+ */
+ public function render_form_after_add_to_cart_with_options( $block_content, $parsed_block, $block ) {
+ $product_id = (int) ( $block->context['postId'] ?? 0 );
+
+ // Only the block for the product being viewed, not those in related products, upsells or other products' Single Product blocks.
+ $product = $product_id && get_queried_object_id() === $product_id ? wc_get_product( $product_id ) : null;
+ if ( '' === $block_content || ! $product ) {
+ return $block_content;
+ }
+
+ ob_start();
+ $this->maybe_render_product_form( $product, true );
+
+ return $this->add_interactivity_to_form( $block_content, (string) ob_get_clean(), $product );
+ }
+
+ /**
+ * Let the Interactivity API show the form for the variation chosen in the block and post its attributes.
+ *
+ * The template is left untouched: the directives are added to its rendered markup.
+ *
+ * @param string $block_content The Add to Cart + Options block content.
+ * @param string $form The rendered form markup.
+ * @param WC_Product $product Product object.
+ * @return string The block content followed by the form.
+ */
+ private function add_interactivity_to_form( string $block_content, string $form, WC_Product $product ): string {
+ $html = new \WP_HTML_Tag_Processor( $form );
+
+ // The form of a variable product starts hidden until an out of stock variation is chosen.
+ if ( ! $product instanceof \WC_Product_Variable || ! $html->next_tag( array( 'class_name' => 'wc_bis_form' ) ) || null === $html->get_attribute( 'hidden' ) ) {
+ return $block_content . $form;
+ }
+
+ // The block renders no variation selector when the product can't be bought, so offer sign-ups for the parent.
+ if ( AddToCartWithOptionsUtils::is_not_purchasable_product( $product ) ) {
+ $html->remove_attribute( 'hidden' );
+
+ return $block_content . $html->get_updated_html();
+ }
+
+ wp_enqueue_script_module( self::SCRIPT_MODULE );
+
+ // The store namespace matches the script module ID.
+ $html->set_attribute( 'data-wp-interactive', self::SCRIPT_MODULE );
+ $html->set_attribute( 'data-wp-bind--hidden', '!state.isVisible' );
+
+ $form_id = wp_unique_id( 'wc-bis-form-' );
+ if ( $html->next_tag( array( 'tag_name' => 'form' ) ) ) {
+ $html->set_attribute( 'id', $form_id );
+ }
+
+ while ( $html->next_tag( array( 'tag_name' => 'input' ) ) ) {
+ if ( 'wc_bis_product_id' === $html->get_attribute( 'name' ) ) {
+ $html->set_attribute( 'data-wp-bind--value', 'woocommerce/products::state.productInContext.id' );
+ break;
+ }
+ }
+
+ $form = $html->get_updated_html();
+
+ // Post the chosen values, so "any" attributes are kept like in the classic form. The inputs sit inside
+ // the block's <form> to read its selected attributes, and the `form` attribute submits them with the BIS form.
+ $attribute_inputs = '';
+ foreach ( array_keys( $product->get_variation_attributes() ) as $attribute_name ) {
+ $attribute_name = (string) $attribute_name;
+ $attribute_inputs .= sprintf(
+ '<input type="hidden" name="%s" form="%s" data-wp-interactive="%s" %s data-wp-bind--value="state.selectedAttributeValue" />',
+ esc_attr( wc_variation_attribute_name( $attribute_name ) ),
+ esc_attr( $form_id ),
+ esc_attr( self::SCRIPT_MODULE ),
+ wp_interactivity_data_wp_context( array( 'attribute' => wc_attribute_label( $attribute_name ) ) )
+ );
+ }
+
+ // The block's own </form> comes first, as forms can't be nested.
+ $block_form_end = stripos( $block_content, '</form>' );
+ if ( false !== $block_form_end ) {
+ $block_content = substr_replace( $block_content, $attribute_inputs, $block_form_end, 0 );
+ }
+
+ return $block_content . $form;
+ }
+
+ /**
+ * Render the BIS form for a product when it is eligible for sign-ups.
+ *
+ * @param WC_Product $product Product object.
+ * @param bool $is_block Whether the form renders for the Add to Cart + Options block.
+ * @return void
+ */
+ private function maybe_render_product_form( WC_Product $product, bool $is_block = false ): void {
+
+ if ( ! Config::allows_signups() || ! is_product() ) {
return;
}
@@ -90,7 +200,10 @@ class ProductPageIntegration {
return;
}
- $this->rendered[ $product->get_id() ] = true;
+ // The block doesn't mark the product as rendered, as its output can be discarded.
+ if ( ! $is_block ) {
+ $this->rendered[ $product->get_id() ] = true;
+ }
$is_variable = $product->is_type( 'variable' );
// Check if the product is in stock.
@@ -108,8 +221,10 @@ class ProductPageIntegration {
return;
}
- // Enqueue the script.
- wp_enqueue_script( 'wc-back-in-stock-form' );
+ // The block is driven by the Interactivity API, see add_interactivity_to_form().
+ if ( ! $is_block ) {
+ wp_enqueue_script( 'wc-back-in-stock-form' );
+ }
$this->render_form( $product );
}
diff --git a/plugins/woocommerce/tests/e2e/playwright.config.ts b/plugins/woocommerce/tests/e2e/playwright.config.ts
index ae717f9dcbc..2617df4acfc 100644
--- a/plugins/woocommerce/tests/e2e/playwright.config.ts
+++ b/plugins/woocommerce/tests/e2e/playwright.config.ts
@@ -291,6 +291,9 @@ const blocksSerialSpecs = [
'**/tests/blocks/cart/cart-checkout-block-taxes.shopper.block_theme.spec.ts',
// Switches the site language, which every spec reads.
'**/tests/blocks/cart/cart-checkout-block-translations.shopper.block_theme.spec.ts',
+ // Turns on Back in Stock Notifications sign-ups, which adds a form to every
+ // out-of-stock product page.
+ '**/tests/blocks/add-to-cart-with-options/back-in-stock-form.block_theme.spec.ts',
// Changes local pickup, shipping methods, "Hide shipping costs until an
// address is entered" and the countries the store ships to, and saves the
// Checkout page template. Most tests also place orders, some for Beanie,
diff --git a/plugins/woocommerce/tests/e2e/tests/blocks/add-to-cart-with-options/back-in-stock-form.block_theme.spec.ts b/plugins/woocommerce/tests/e2e/tests/blocks/add-to-cart-with-options/back-in-stock-form.block_theme.spec.ts
new file mode 100644
index 00000000000..3bd9fab9420
--- /dev/null
+++ b/plugins/woocommerce/tests/e2e/tests/blocks/add-to-cart-with-options/back-in-stock-form.block_theme.spec.ts
@@ -0,0 +1,210 @@
+/**
+ * External dependencies
+ */
+import { randomUUID } from 'crypto';
+import type { Page } from '@playwright/test';
+import {
+ test as base,
+ expect,
+ getProductAttributeIds,
+ guestFile,
+ wpCLI,
+} from '@woocommerce/e2e-utils';
+
+/**
+ * Internal dependencies
+ */
+import {
+ BIS_FEATURE_OPTION,
+ BIS_OPTIONS,
+ bisFormLocator,
+ bisNotice,
+ bisTargetProductInput,
+ signUpOnProductPage,
+ uniqueGuestEmail,
+} from '../../../utils/back-in-stock-notifications';
+
+type Product = { id: number; name: string; slug: string; permalink: string };
+
+const test = base.extend< {
+ // Creates a product and a `single-product-<slug>` template that renders it
+ // with the Add to Cart + Options block. The serial project's database reset
+ // removes both after the test.
+ createProductPage: (
+ data: Record< string, unknown >
+ ) => Promise< Product >;
+} >( {
+ createProductPage: async ( { requestUtils }, use ) => {
+ // eslint-disable-next-line react-hooks/rules-of-hooks -- Playwright's fixture `use`, not a React hook.
+ await use( async ( data ) => {
+ const product = await requestUtils.rest< Product >( {
+ method: 'POST',
+ path: 'wc/v3/products',
+ data: {
+ name: `BIS Block ${ randomUUID().slice( 0, 8 ) }`,
+ regular_price: '10',
+ ...data,
+ },
+ } );
+ await requestUtils.createTemplate( 'wp_template', {
+ slug: `single-product-${ product.slug }`,
+ title: `Single Product ${ product.slug }`,
+ content:
+ '<!-- wp:woocommerce/store-notices /--><!-- wp:woocommerce/add-to-cart-with-options /-->',
+ } );
+ return product;
+ } );
+ },
+} );
+
+test.describe( 'Add to Cart + Options Block: Back in Stock form', () => {
+ test.use( { storageState: guestFile } );
+
+ test.beforeEach( async () => {
+ await wpCLI( `option update ${ BIS_FEATURE_OPTION } yes` );
+ await wpCLI( `option update ${ BIS_OPTIONS.allowSignups } yes` );
+ } );
+
+ test( 'renders after the block for an out-of-stock simple product', async ( {
+ page,
+ createProductPage,
+ } ) => {
+ const product = await createProductPage( {
+ type: 'simple',
+ stock_status: 'outofstock',
+ } );
+ const email = uniqueGuestEmail( 'bis-block-simple' );
+
+ await page.goto( product.permalink );
+
+ await expect( bisFormLocator( page ) ).toBeVisible();
+
+ await signUpOnProductPage( page, { email } );
+
+ await expect(
+ page.getByText( bisNotice.success( product.name ) )
+ ).toBeVisible();
+ } );
+
+ test.describe( 'variable product', () => {
+ let product: Product;
+ let outOfStockVariationId: number;
+
+ test.beforeEach( async ( { requestUtils, createProductPage } ) => {
+ const { colorAttributeId: colorId, sizeAttributeId: sizeId } =
+ await getProductAttributeIds();
+
+ product = await createProductPage( {
+ type: 'variable',
+ attributes: [
+ {
+ id: colorId,
+ variation: true,
+ visible: true,
+ options: [ 'Blue', 'Red' ],
+ },
+ {
+ id: sizeId,
+ variation: true,
+ visible: true,
+ options: [ 'Small', 'Large' ],
+ },
+ ],
+ } );
+
+ // Both variations take "any" size.
+ const { create } = await requestUtils.rest< {
+ create: { id: number }[];
+ } >( {
+ method: 'POST',
+ path: `wc/v3/products/${ product.id }/variations/batch`,
+ data: {
+ create: [
+ { option: 'Blue', stock_status: 'outofstock' },
+ { option: 'Red', stock_status: 'instock' },
+ ].map( ( { option, stock_status } ) => ( {
+ regular_price: '10',
+ stock_status,
+ attributes: [
+ { id: colorId, option },
+ { id: sizeId, option: '' },
+ ],
+ } ) ),
+ },
+ } );
+ outOfStockVariationId = create[ 0 ].id;
+ } );
+
+ const chip = ( page: Page, attribute: string, option: string ) =>
+ page
+ .locator( '.wp-block-add-to-cart-with-options' )
+ .getByRole( 'radiogroup', { name: attribute } )
+ .getByRole( 'radio', { name: option, exact: true } );
+
+ test( 'signs up for the selected out-of-stock variation and its "any" attribute', async ( {
+ page,
+ } ) => {
+ const email = uniqueGuestEmail( 'bis-block-variation' );
+ const form = bisFormLocator( page );
+
+ await page.goto( product.permalink );
+ await expect( form ).toBeHidden();
+
+ await chip( page, 'Color', 'Blue' ).click();
+ await chip( page, 'Size', 'Large' ).click();
+
+ await expect( form ).toBeVisible();
+ await expect( bisTargetProductInput( page ) ).toHaveValue(
+ String( outOfStockVariationId )
+ );
+ // Rendered in the block's <form> and posted with the Back in Stock form.
+ await expect(
+ page.locator(
+ '.wp-block-add-to-cart-with-options input[name="attribute_pa_size"][form]'
+ )
+ ).toHaveValue( 'large' );
+
+ const signupRequest = page.waitForRequest(
+ ( request ) =>
+ request.method() === 'POST' &&
+ ( request.postData() ?? '' ).includes( 'wc_bis_product_id' )
+ );
+ await signUpOnProductPage( page, { email } );
+ const posted = new URLSearchParams(
+ ( await signupRequest ).postData() ?? ''
+ );
+
+ await expect(
+ page.getByText( /You have successfully signed up!/ )
+ ).toBeVisible();
+ expect( posted.get( 'wc_bis_product_id' ) ).toBe(
+ String( outOfStockVariationId )
+ );
+ expect( posted.get( 'attribute_pa_size' ) ).toBe( 'large' );
+ } );
+
+ test( 'hides the form for an in-stock variation and a cleared selection', async ( {
+ page,
+ } ) => {
+ const form = bisFormLocator( page );
+
+ await page.goto( product.permalink );
+ await chip( page, 'Color', 'Blue' ).click();
+ await chip( page, 'Size', 'Large' ).click();
+ await expect( form ).toBeVisible();
+
+ await chip( page, 'Color', 'Red' ).click();
+ await expect( form ).toBeHidden();
+
+ await chip( page, 'Color', 'Blue' ).click();
+ await expect( form ).toBeVisible();
+
+ // Clicking the selected chip clears it.
+ await chip( page, 'Size', 'Large' ).click();
+ await expect( form ).toBeHidden();
+ await expect( bisTargetProductInput( page ) ).toHaveValue(
+ String( product.id )
+ );
+ } );
+ } );
+} );
diff --git a/plugins/woocommerce/tests/php/src/Internal/StockNotifications/Frontend/ProductPageIntegrationTest.php b/plugins/woocommerce/tests/php/src/Internal/StockNotifications/Frontend/ProductPageIntegrationTest.php
index c8ef997283e..c6b85edf8fe 100644
--- a/plugins/woocommerce/tests/php/src/Internal/StockNotifications/Frontend/ProductPageIntegrationTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/StockNotifications/Frontend/ProductPageIntegrationTest.php
@@ -127,15 +127,44 @@ class ProductPageIntegrationTest extends WC_Unit_Test_Case {
}
/**
- * @testdox Should not render the form inside the Add to Cart + Options block so it keeps its Interactivity API form.
+ * @testdox Should render an interactive form after the Add to Cart + Options block so it keeps its Interactivity API form.
*/
- public function test_form_is_not_rendered_inside_add_to_cart_with_options_block(): void {
+ public function test_interactive_form_is_rendered_after_add_to_cart_with_options_block(): void {
$product_id = $this->create_and_visit_variable_product();
$markup = do_blocks( '<!-- wp:woocommerce/single-product {"productId":' . $product_id . '} --><!-- wp:woocommerce/add-to-cart-with-options /--><!-- /wp:woocommerce/single-product -->' );
$this->assertStringContainsString( 'data-wp-on--submit', $markup, 'The Add to Cart + Options block should keep its Interactivity API form when sign-ups are enabled.' );
- $this->assertStringNotContainsString( 'wc_bis_form', $markup, 'The Back in Stock form should not render inside the Add to Cart + Options block.' );
+ $this->assertSame( 1, substr_count( $markup, 'class="wc_bis_form"' ), 'The Back in Stock form should render once.' );
+ $this->assertGreaterThan( strpos( $markup, '</form>' ), strpos( $markup, 'class="wc_bis_form"' ), 'The Back in Stock form should render outside the block form.' );
+
+ // The attribute inputs sit inside the block form, to read its selected attributes.
+ $block_form = new \WP_HTML_Tag_Processor( substr( $markup, 0, strpos( $markup, '</form>' ) ) );
+ $this->assertTrue( $block_form->next_tag( array( 'class_name' => 'wc-block-add-to-cart-with-options' ) ), 'The block form should render.' );
+ $attribute_input = null;
+ while ( $block_form->next_tag( 'input' ) ) {
+ if ( 'attribute_pa_color' === $block_form->get_attribute( 'name' ) ) {
+ $attribute_input = array(
+ 'form' => $block_form->get_attribute( 'form' ),
+ 'value' => $block_form->get_attribute( 'data-wp-bind--value' ),
+ );
+ }
+ }
+ $this->assertSame( 'state.selectedAttributeValue', $attribute_input['value'] ?? null, 'The block form should hold the chosen attributes.' );
+
+ $html = new \WP_HTML_Tag_Processor( $markup );
+ $html->next_tag( array( 'class_name' => 'wc_bis_form' ) );
+ $this->assertNotNull( $html->get_attribute( 'hidden' ), 'The form should stay hidden until an out of stock variation is chosen.' );
+ $this->assertSame( 'woocommerce/back-in-stock-form', $html->get_attribute( 'data-wp-interactive' ), 'The form should be driven by the Interactivity API.' );
+
+ $html->next_tag( 'form' );
+ $this->assertSame( $html->get_attribute( 'id' ), $attribute_input['form'] ?? '', 'The attribute inputs should be posted with the Back in Stock form.' );
+
+ $bound_inputs = array();
+ while ( $html->next_tag( 'input' ) ) {
+ $bound_inputs[ $html->get_attribute( 'name' ) ] = $html->get_attribute( 'data-wp-bind--value' );
+ }
+ $this->assertSame( 'woocommerce/products::state.productInContext.id', $bound_inputs['wc_bis_product_id'] ?? null, 'The form should target the chosen variation.' );
}
/**
@@ -149,18 +178,101 @@ class ProductPageIntegrationTest extends WC_Unit_Test_Case {
$markup = ob_get_clean();
$this->assertStringContainsString( 'wc_bis_form', $markup, 'The Back in Stock form should render when the hook fires from a classic template.' );
+ $this->assertStringNotContainsString( 'data-wp-', $markup, 'The classic form should not carry Interactivity API directives.' );
}
/**
- * @testdox Should not render the form for an out of stock simple product inside the Add to Cart + Options block.
+ * @testdox Should render a visible form for an out of stock simple product after the Add to Cart + Options block.
*/
- public function test_form_is_not_rendered_for_simple_product_inside_add_to_cart_with_options_block(): void {
+ public function test_form_is_rendered_for_simple_product_after_add_to_cart_with_options_block(): void {
$product_id = $this->create_and_visit_out_of_stock_simple_product();
$markup = do_blocks( '<!-- wp:woocommerce/single-product {"productId":' . $product_id . '} --><!-- wp:woocommerce/add-to-cart-with-options /--><!-- /wp:woocommerce/single-product -->' );
$this->assertStringContainsString( 'data-wp-on--submit', $markup, 'The Add to Cart + Options block should keep its Interactivity API form for an out of stock simple product.' );
- $this->assertStringNotContainsString( 'wc_bis_form', $markup, 'The Back in Stock form should not render inside the Add to Cart + Options block for a simple product.' );
+ $this->assertGreaterThan( strpos( $markup, '</form>' ), strpos( $markup, 'class="wc_bis_form"' ), 'The Back in Stock form should render outside the block form.' );
+
+ $form = substr( $markup, strpos( $markup, '<div class="wc_bis_form"' ) );
+ $html = new \WP_HTML_Tag_Processor( $form );
+ $this->assertTrue( $html->next_tag( array( 'class_name' => 'wc_bis_form' ) ), 'The Back in Stock form should render.' );
+ $this->assertNull( $html->get_attribute( 'hidden' ), 'The form should be visible.' );
+ $this->assertStringNotContainsString( 'woocommerce/back-in-stock-form', $form, 'A simple product form needs no Interactivity API store.' );
+ }
+
+ /**
+ * @testdox Should render a visible form for the parent product when no variation can be bought, as the block shows no variation selector.
+ */
+ public function test_form_is_rendered_for_parent_when_no_variation_can_be_bought(): void {
+ $fixtures = new FixtureData();
+ $variable_product = $fixtures->get_variable_product(
+ array(),
+ array( $fixtures->get_product_attribute( 'color', array( 'red', 'blue' ) ) )
+ );
+ $product_id = $variable_product->get_id();
+ foreach ( array( 'red-slug', 'blue-slug' ) as $color ) {
+ $fixtures->get_variation_product(
+ $product_id,
+ array( 'pa_color' => $color ),
+ array(
+ 'regular_price' => 10,
+ 'stock_status' => ProductStockStatus::OUT_OF_STOCK,
+ )
+ );
+ }
+ \WC_Product_Variable::sync( $product_id );
+ $this->go_to( get_permalink( $product_id ) );
+ $GLOBALS['product'] = wc_get_product( $product_id ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+
+ $markup = do_blocks( '<!-- wp:woocommerce/single-product {"productId":' . $product_id . '} --><!-- wp:woocommerce/add-to-cart-with-options /--><!-- /wp:woocommerce/single-product -->' );
+
+ $this->assertSame( 1, substr_count( $markup, 'class="wc_bis_form"' ), 'The Back in Stock form should render once.' );
+ $this->assertStringNotContainsString( 'form="wc-bis-form-', $markup, 'Without a variation selector there are no attributes to post.' );
+
+ $html = new \WP_HTML_Tag_Processor( $markup );
+ $html->next_tag( array( 'class_name' => 'wc_bis_form' ) );
+ $this->assertNull( $html->get_attribute( 'hidden' ), 'The form should be visible.' );
+ $this->assertNull( $html->get_attribute( 'data-wp-interactive' ), 'The form needs no Interactivity API store.' );
+
+ $posted_product_id = null;
+ while ( $html->next_tag( 'input' ) ) {
+ if ( 'wc_bis_product_id' === $html->get_attribute( 'name' ) ) {
+ $posted_product_id = $html->get_attribute( 'value' );
+ }
+ }
+ $this->assertSame( (string) $product_id, $posted_product_id, 'The sign-up should be for the parent product.' );
+ }
+
+ /**
+ * @testdox Should not render the form for an Add to Cart + Options block of another product than the one being viewed.
+ */
+ public function test_form_is_not_rendered_for_add_to_cart_with_options_block_of_another_product(): void {
+ $this->create_and_visit_out_of_stock_simple_product();
+ $other_product_id = ( new FixtureData() )->get_simple_product(
+ array(
+ 'regular_price' => 10,
+ 'stock_status' => ProductStockStatus::OUT_OF_STOCK,
+ )
+ )->get_id();
+
+ $markup = do_blocks( '<!-- wp:woocommerce/single-product {"productId":' . $other_product_id . '} --><!-- wp:woocommerce/add-to-cart-with-options /--><!-- /wp:woocommerce/single-product -->' );
+
+ $this->assertStringNotContainsString( 'wc_bis_form', $markup, 'Blocks for other products, e.g. in related products, should not get a Back in Stock form.' );
+ }
+
+ /**
+ * @testdox Should not render a second form after the Add to Cart + Options block when the classic hook already rendered one.
+ */
+ public function test_form_is_not_rendered_twice_when_classic_hook_rendered_it_first(): void {
+ $product_id = $this->create_and_visit_out_of_stock_simple_product();
+
+ ob_start();
+ do_action( 'woocommerce_simple_add_to_cart' );
+ $classic_markup = ob_get_clean();
+
+ $block_markup = do_blocks( '<!-- wp:woocommerce/single-product {"productId":' . $product_id . '} --><!-- wp:woocommerce/add-to-cart-with-options /--><!-- /wp:woocommerce/single-product -->' );
+
+ $this->assertStringContainsString( 'wc_bis_form', $classic_markup, 'The classic hook should render the form.' );
+ $this->assertStringNotContainsString( 'wc_bis_form', $block_markup, 'The block should not render a second form for the same product.' );
}
/**