Skip to content

Add to Cart with Options: Ensure minus button is disabled, unfocusable, and unclickable at minimum quantity in QuantityStepper #59488

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: trunk
Choose a base branch
from

Conversation

amitraj2203
Copy link
Contributor

@amitraj2203 amitraj2203 commented Jul 7, 2025

Submission Review Guidelines:

Changes proposed in this Pull Request:

  • This PR is the third part of the fix for Issue Tab navigation inconsistency between QuantityStepper and QuantitySelector components #58011, following up on the work started in previous PR (adjust tab navigation between QuantityStepper and QuantitySelector).
  • This update specifically applies to the non-blockified Add to Cart with Options block
  • This PR addresses the expected accessibility and UX behavior of the minus (-) button in the QuantityStepper component by:
    • Ensuring the minus (-) button becomes:
      • Disabled
      • Unfocusable via keyboard (tab)
      • Unclickable
    • When the quantity equals the minimum allowed value.

These changes align the behavior of QuantityStepper with QuantitySelector for consistency across components.

Closes #58011

Screenshots or screen recordings:

59488.mov

How to test the changes in this Pull Request:

Using the WooCommerce Testing Instructions Guide, include your detailed testing instructions:

  1. Go to Appearance > Editor > Templates > Single Product, and make sure the non-blockified Add to Cart + Options block is selected with stepper mode.
  2. View any product on the frontend. (Single or Grouped)
  3. Use the QuantityStepper to set the quantity to the minimum allowed value (e.g., 1).
  4. Confirm the following:
  5. The minus (-) button appears visually disabled.
  6. Pressing Tab does not focus the minus button.
  7. Clicking the button (with mouse or keyboard) does not change quantity or trigger events.

Changelog entry

  • Automatically create a changelog entry from the details below.
  • This Pull Request does not require a changelog entry. (Comment required below)
Changelog Entry Details

Significance

  • Patch
  • Minor
  • Major

Type

  • Fix - Fixes an existing bug
  • Add - Adds functionality
  • Update - Update existing functionality
  • Dev - Development related task
  • Tweak - A minor adjustment to the codebase
  • Performance - Address performance issues
  • Enhancement - Improvement to existing functionality

Message

Changelog Entry Comment

Comment

@github-actions github-actions bot added plugin: woocommerce Issues related to the WooCommerce Core plugin. type: community contribution labels Jul 7, 2025
Copy link
Contributor

coderabbitai bot commented Jul 7, 2025

📝 Walkthrough

Walkthrough

The changes refactor and centralize quantity state management for WooCommerce's add-to-cart form, both in the frontend TypeScript logic and PHP rendering. They introduce a typed context for product and quantity constraints, update UI bindings for quantity steppers, and enhance grouped product support with contextual data and new helper methods.

Changes

File(s) Change Summary
.../add-to-cart-form/frontend.ts Refactored quantity handling to use a typed Context object; added computed getters and actions for state; unified quantity constraints and input synchronization.
.../AddToCartForm.php Updated add_steppers for new input bindings and disabled state; added filter_grouped_product_quantity_column and get_quantity_constraints methods; enhanced render logic for context and grouped products.
.../changelog/fix-issue-58011-addtocartform Fixed QuantityStepper minus button to be disabled, unfocusable, and unclickable at minimum quantity.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant InputField
    participant JSStore
    participant Context

    User->>InputField: Change quantity (click or input)
    InputField->>JSStore: handleInputChange(event)
    JSStore->>Context: Update quantity for product/child
    JSStore->>InputField: Update value, dispatch change event
    JSStore->>JSStore: Compute allowsIncrease/allowsDecrease
    JSStore->>InputField: Update stepper button states (disabled/enabled)
Loading
sequenceDiagram
    participant PHP_Render
    participant GroupedProduct
    participant ChildProduct
    participant Constraints
    participant HTML

    PHP_Render->>GroupedProduct: Get child products
    loop For each ChildProduct
        PHP_Render->>Constraints: get_quantity_constraints(child, true)
        Constraints-->>PHP_Render: {min, max, step}
        PHP_Render->>HTML: Wrap input with context data if eligible
    end
    PHP_Render->>HTML: Add data-wp-context and data-wp-interactive to wrapper div
Loading

Possibly related PRs


📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c4f4472 and 7194eb4.

📒 Files selected for processing (1)
  • plugins/woocommerce/src/Blocks/BlockTypes/AddToCartForm.php (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • plugins/woocommerce/src/Blocks/BlockTypes/AddToCartForm.php
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
plugins/woocommerce/client/blocks/assets/js/blocks/product-elements/add-to-cart-form/frontend.ts (1)

7-16: Consider making the Context type more robust with proper null handling.

The quantityConstraints property could be undefined based on the usage in the code, but the type doesn't reflect this. Also consider documenting what each property represents.

-export type Context = {
-	productId: number;
-	productType: string;
-	quantity: Record< number, number >;
-	childProductId: number;
-	quantityConstraints: Record<
-		number,
-		{ min: number; max: number | null; step: number }
-	>;
-};
+export type Context = {
+	/** The main product ID */
+	productId: number;
+	/** The product type (e.g., 'simple', 'grouped', 'variation') */
+	productType: string;
+	/** Map of product/child product IDs to their current quantities */
+	quantity: Record< number, number >;
+	/** The current child product ID for grouped products */
+	childProductId?: number;
+	/** Map of product/child product IDs to their quantity constraints */
+	quantityConstraints?: Record<
+		number,
+		{ min: number; max: number | null; step: number }
+	>;
+};
plugins/woocommerce/src/Blocks/BlockTypes/AddToCartForm.php (2)

76-92: Consider a more robust approach than regex for DOM manipulation.

Using regex to parse and modify HTML is fragile and can break if the HTML structure changes. Consider using WP_HTML_Tag_Processor for more reliable DOM manipulation, similar to how you're using it in add_stepper_classes_to_add_to_cart_form_input.

private function add_steppers( $product_html, $product_name ) {
    $html = new \WP_HTML_Tag_Processor( $product_html );
    
    // Add change handler to quantity inputs
    while ( $html->next_tag( array( 'tag_name' => 'input' ) ) ) {
        $id = $html->get_attribute( 'id' );
        if ( $id && strpos( $id, 'quantity_' ) === 0 ) {
            $html->set_attribute( 'data-wp-on--change', 'actions.handleInputChange' );
            
            // Get the current HTML and insert buttons after this input
            $input_html = $html->get_updated_html();
            $minus_button = sprintf(
                '<button aria-label="%s" type="button" data-wp-on--click="actions.removeQuantity" data-wp-bind--disabled="!state.allowsDecrease" class="wc-block-components-quantity-selector__button wc-block-components-quantity-selector__button--minus">−</button>',
                esc_attr( sprintf( __( 'Reduce quantity of %s', 'woocommerce' ), $product_name ) )
            );
            $plus_button = sprintf(
                '<button aria-label="%s" type="button" data-wp-on--click="actions.addQuantity" data-wp-bind--disabled="!state.allowsIncrease" class="wc-block-components-quantity-selector__button wc-block-components-quantity-selector__button--plus">+</button>',
                esc_attr( sprintf( __( 'Increase quantity of %s', 'woocommerce' ), $product_name ) )
            );
            // Use a more targeted approach to insert buttons
        }
    }
    
    return $html->get_updated_html();
}

94-119: Document the filtering logic for grouped products.

The method filters out products that have options, but this behavior isn't documented. Consider adding a comment explaining why products with options are excluded.

public function filter_grouped_product_quantity_column( $value, $grouped_product_child ) {
	// Only wrap if stepper style is enabled and the child is purchasable and in stock.
	if ( ! Features::is_enabled( 'add-to-cart-with-options-stepper-layout' ) ) {
		return $value;
	}
+	// Products with options (e.g., variations) require additional UI for selection,
+	// so they're excluded from the simplified stepper interface.
	if ( ! $grouped_product_child->is_purchasable() || $grouped_product_child->has_options() || ! $grouped_product_child->is_in_stock() ) {
		return $value;
	}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5a29dcb and 6af766e.

📒 Files selected for processing (2)
  • plugins/woocommerce/client/blocks/assets/js/blocks/product-elements/add-to-cart-form/frontend.ts (4 hunks)
  • plugins/woocommerce/src/Blocks/BlockTypes/AddToCartForm.php (5 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: CR
PR: woocommerce/woocommerce#0
File: .cursor/rules/generate-pr-description.mdc:0-0
Timestamp: 2025-06-30T09:26:55.361Z
Learning: Provide clear, step-by-step instructions for how to test the changes in the PR description.
Learnt from: Aljullu
PR: woocommerce/woocommerce#58809
File: plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php:222-225
Timestamp: 2025-06-13T17:11:13.732Z
Learning: In `plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php`, the team intentionally relies on toggling the `disabled` CSS class (via `data-wp-class--disabled`) instead of binding the `disabled` attribute, to mirror the behavior of the classic WooCommerce template.
Learnt from: samueljseay
PR: woocommerce/woocommerce#59051
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/mini-cart-contents/inner-blocks/mini-cart-footer-block/index.tsx:66-70
Timestamp: 2025-06-23T05:47:52.696Z
Learning: For WooCommerce mini-cart blocks in plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/, the standardized conditional pattern for experimental features should be `if ( isExperimentalMiniCartEnabled() ) { blockSettings.save = () => <InnerBlocks.Content />; }` - defaulting to the traditional Save component and only overriding when the experimental feature is enabled.
Learnt from: samueljseay
PR: woocommerce/woocommerce#58716
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/iapi-frontend.ts:83-101
Timestamp: 2025-06-17T07:07:53.443Z
Learning: In WooCommerce blocks, when porting existing code patterns that have known issues (like parseInt truncating decimal money values), maintain consistency with existing implementation rather than making isolated fixes. The preference is for systematic refactoring approaches (like broader Dinero adoption) over piecemeal changes.
Learnt from: ralucaStan
PR: woocommerce/woocommerce#58782
File: plugins/woocommerce/client/blocks/assets/js/base/utils/render-frontend.tsx:0-0
Timestamp: 2025-06-16T16:12:12.148Z
Learning: For WooCommerce checkout blocks, lazy loading was removed in favor of direct imports to prevent sequential "popping" effects during component loading. This approach prioritizes user experience over code splitting, with minimal bundle size impact and improved performance (1.7s to 1.1s speed score improvement). The checkout flow benefits from having all components load together rather than incrementally.
Learnt from: samueljseay
PR: woocommerce/woocommerce#58716
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/iapi-frontend.ts:78-96
Timestamp: 2025-06-18T06:05:25.472Z
Learning: In WooCommerce mini cart implementation, the cart state is server-populated before JavaScript initialization, so wooStoreState.cart and wooStoreState.cart.totals will be available on first render without requiring null-safe guards.
Learnt from: mikejolley
PR: woocommerce/woocommerce#57961
File: plugins/woocommerce/includes/class-wc-session-handler.php:302-333
Timestamp: 2025-06-19T11:58:57.484Z
Learning: In WooCommerce's session handler, the cart merging behavior was revised to always merge guest and user carts when both contain items, rather than having the guest cart take precedence. The migrate_cart_data() method in class-wc-session-handler.php implements this by using array_merge() to combine both carts when neither is empty.
Learnt from: prettyboymp
PR: woocommerce/woocommerce#59048
File: .github/workflows/cherry-pick-milestoned-prs.yml:60-83
Timestamp: 2025-06-26T12:45:40.709Z
Learning: WooCommerce uses WordPress versioning conventions where minor versions in X.Y.Z format are constrained to 0-9 (Y cannot exceed 9). This means version increment logic should reset minor to 0 and increment major when minor reaches 9, rather than allowing two-digit minor versions like 9.10 or 9.11.
Learnt from: triple0t
PR: woocommerce/woocommerce#59186
File: packages/js/email-editor/src/store/initial-state.ts:9-10
Timestamp: 2025-06-26T12:13:32.062Z
Learning: In WooCommerce email editor store initialization (packages/js/email-editor/src/store/initial-state.ts), the current_post_id and current_post_type from window.WooCommerceEmailEditor are required parameters that should cause explicit errors if missing, rather than using fallback values or optional chaining. The design preference is to fail fast when critical initialization data is unavailable.
Learnt from: vladolaru
PR: woocommerce/woocommerce#58784
File: plugins/woocommerce/client/admin/client/settings-payments/onboarding/components/stepper/index.tsx:57-67
Timestamp: 2025-06-20T13:08:44.017Z
Learning: For WooCommerce Payments onboarding step tracking in useEffect hooks, only include the active step in the dependency array, not the context object. The sessionEntryPoint is static throughout the onboarding session and tracking should only fire on actual step navigation, not context changes.
Learnt from: opr
PR: woocommerce/woocommerce#0
File: :0-0
Timestamp: 2025-06-20T17:38:16.565Z
Learning: WooCommerce legacy JavaScript files in plugins/woocommerce/client/legacy/js/ must use older JavaScript syntax and cannot use modern features like optional chaining (?.) due to browser compatibility requirements. Explicit null checking with && operators should be used instead.
plugins/woocommerce/client/blocks/assets/js/blocks/product-elements/add-to-cart-form/frontend.ts (10)
Learnt from: samueljseay
PR: woocommerce/woocommerce#58716
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/iapi-frontend.ts:83-101
Timestamp: 2025-06-17T07:07:53.443Z
Learning: In WooCommerce blocks, when porting existing code patterns that have known issues (like parseInt truncating decimal money values), maintain consistency with existing implementation rather than making isolated fixes. The preference is for systematic refactoring approaches (like broader Dinero adoption) over piecemeal changes.
Learnt from: samueljseay
PR: woocommerce/woocommerce#59051
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/mini-cart-contents/inner-blocks/mini-cart-footer-block/index.tsx:66-70
Timestamp: 2025-06-23T05:47:52.696Z
Learning: For WooCommerce mini-cart blocks in plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/, the standardized conditional pattern for experimental features should be `if ( isExperimentalMiniCartEnabled() ) { blockSettings.save = () => <InnerBlocks.Content />; }` - defaulting to the traditional Save component and only overriding when the experimental feature is enabled.
Learnt from: vladolaru
PR: woocommerce/woocommerce#58784
File: plugins/woocommerce/client/admin/client/settings-payments/components/other-payment-gateways/other-payment-gateways.tsx:43-50
Timestamp: 2025-06-18T07:56:06.961Z
Learning: In plugins/woocommerce/client/admin/client/settings-payments/components/other-payment-gateways/other-payment-gateways.tsx, the user vladolaru prefers to keep the current setUpPlugin function signature with optional positional context parameter rather than refactoring to an options object or making context required.
Learnt from: vladolaru
PR: woocommerce/woocommerce#58784
File: plugins/woocommerce/client/admin/client/settings-payments/onboarding/components/stepper/index.tsx:57-67
Timestamp: 2025-06-20T13:08:44.017Z
Learning: For WooCommerce Payments onboarding step tracking in useEffect hooks, only include the active step in the dependency array, not the context object. The sessionEntryPoint is static throughout the onboarding session and tracking should only fire on actual step navigation, not context changes.
Learnt from: samueljseay
PR: woocommerce/woocommerce#58716
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/iapi-frontend.ts:78-96
Timestamp: 2025-06-18T06:05:25.472Z
Learning: In WooCommerce mini cart implementation, the cart state is server-populated before JavaScript initialization, so wooStoreState.cart and wooStoreState.cart.totals will be available on first render without requiring null-safe guards.
Learnt from: ralucaStan
PR: woocommerce/woocommerce#58782
File: plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/product-details/style.scss:21-26
Timestamp: 2025-06-13T15:24:45.923Z
Learning: In WooCommerce blocks, bold styling for `.wc-block-components-product-details__name` should be scoped only to the Cart block (`.wc-block-cart__main`); on the Checkout block, product names are not bold because prices are highlighted instead.
Learnt from: triple0t
PR: woocommerce/woocommerce#59186
File: packages/js/email-editor/src/store/initial-state.ts:9-10
Timestamp: 2025-06-26T12:13:32.062Z
Learning: In WooCommerce email editor store initialization (packages/js/email-editor/src/store/initial-state.ts), the current_post_id and current_post_type from window.WooCommerceEmailEditor are required parameters that should cause explicit errors if missing, rather than using fallback values or optional chaining. The design preference is to fail fast when critical initialization data is unavailable.
Learnt from: ralucaStan
PR: woocommerce/woocommerce#58782
File: plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/customer-address.tsx:76-90
Timestamp: 2025-06-13T13:37:35.793Z
Learning: In plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/customer-address.tsx, the `shouldAnimate` flag is expected to be `false` only on initial render and may remain `true` after the first edit; it does not need to be reset.
Learnt from: Aljullu
PR: woocommerce/woocommerce#58809
File: plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php:222-225
Timestamp: 2025-06-13T17:11:13.732Z
Learning: In `plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php`, the team intentionally relies on toggling the `disabled` CSS class (via `data-wp-class--disabled`) instead of binding the `disabled` attribute, to mirror the behavior of the classic WooCommerce template.
Learnt from: opr
PR: woocommerce/woocommerce#0
File: :0-0
Timestamp: 2025-06-20T17:38:16.565Z
Learning: WooCommerce legacy JavaScript files in plugins/woocommerce/client/legacy/js/ must use older JavaScript syntax and cannot use modern features like optional chaining (?.) due to browser compatibility requirements. Explicit null checking with && operators should be used instead.
plugins/woocommerce/src/Blocks/BlockTypes/AddToCartForm.php (8)
Learnt from: Aljullu
PR: woocommerce/woocommerce#58809
File: plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php:222-225
Timestamp: 2025-06-13T17:11:13.732Z
Learning: In `plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php`, the team intentionally relies on toggling the `disabled` CSS class (via `data-wp-class--disabled`) instead of binding the `disabled` attribute, to mirror the behavior of the classic WooCommerce template.
Learnt from: samueljseay
PR: woocommerce/woocommerce#58716
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/iapi-frontend.ts:83-101
Timestamp: 2025-06-17T07:07:53.443Z
Learning: In WooCommerce blocks, when porting existing code patterns that have known issues (like parseInt truncating decimal money values), maintain consistency with existing implementation rather than making isolated fixes. The preference is for systematic refactoring approaches (like broader Dinero adoption) over piecemeal changes.
Learnt from: samueljseay
PR: woocommerce/woocommerce#59051
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/mini-cart-contents/inner-blocks/mini-cart-footer-block/index.tsx:66-70
Timestamp: 2025-06-23T05:47:52.696Z
Learning: For WooCommerce mini-cart blocks in plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/, the standardized conditional pattern for experimental features should be `if ( isExperimentalMiniCartEnabled() ) { blockSettings.save = () => <InnerBlocks.Content />; }` - defaulting to the traditional Save component and only overriding when the experimental feature is enabled.
Learnt from: ralucaStan
PR: woocommerce/woocommerce#58782
File: plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/product-details/style.scss:21-26
Timestamp: 2025-06-13T15:24:45.923Z
Learning: In WooCommerce blocks, bold styling for `.wc-block-components-product-details__name` should be scoped only to the Cart block (`.wc-block-cart__main`); on the Checkout block, product names are not bold because prices are highlighted instead.
Learnt from: mreishus
PR: woocommerce/woocommerce#58891
File: plugins/woocommerce/src/Blocks/Utils/BlocksSharedState.php:0-0
Timestamp: 2025-06-16T21:59:26.255Z
Learning: In WooCommerce's CartSchema::get_item_response() method, when called in the context of BlocksSharedState::register_cart_interactivity(), the method returns a plain array rather than a WP_REST_Response object, making it directly suitable for wp_interactivity_state() without needing to call ->get_data().
Learnt from: gigitux
PR: woocommerce/woocommerce#58902
File: plugins/woocommerce/client/blocks/assets/js/blocks/product-specifications/edit.tsx:205-206
Timestamp: 2025-06-17T12:40:54.118Z
Learning: In WordPress blocks, when there's a styling mismatch between editor and frontend, check if the PHP renderer (like in `ProductSpecifications.php`) adds specific classes to the output. If so, add those same classes to the `useBlockProps` className in the editor component (like in `edit.tsx`) to ensure consistent styling. For example, adding `wp-block-table` class to both frontend and editor ensures core table styles and theme customizations apply consistently.
Learnt from: samueljseay
PR: woocommerce/woocommerce#59142
File: plugins/woocommerce/src/Blocks/BlockTypes/MiniCart.php:594-602
Timestamp: 2025-06-25T06:51:41.381Z
Learning: WooCommerce block templates have a predictable structure where each block has one top-level div with wp-block-woocommerce- class containing arbitrary nested content that should be preserved.
Learnt from: Aljullu
PR: woocommerce/woocommerce#58845
File: plugins/woocommerce/src/Blocks/BlockTypes/AddToCartWithOptions/Utils.php:128-140
Timestamp: 2025-06-16T11:06:45.637Z
Learning: In WooCommerce, the `$product->is_in_stock()` method returns `true` when backorders are allowed, even if the actual stock quantity is 0 or negative. This means the method already considers backorder status when determining stock availability.
🔇 Additional comments (4)
plugins/woocommerce/client/blocks/assets/js/blocks/product-elements/add-to-cart-form/frontend.ts (3)

24-24: Good selector specificity improvement.

The more specific class name reduces the risk of unintended selector matches.


96-107: Well-implemented reactive state getters.

The state getters correctly implement the logic to determine when increment/decrement buttons should be disabled based on quantity constraints. This directly addresses the PR objective of ensuring the minus button is disabled at minimum quantity.


158-172: Good addition of input change handler.

The handleInputChange action ensures that manual quantity input changes are properly synchronized with the context state, maintaining consistency between the DOM and the reactive state.

plugins/woocommerce/src/Blocks/BlockTypes/AddToCartForm.php (1)

336-371: Well-structured context building and proper JSON encoding.

The context building logic correctly handles both grouped and non-grouped products, providing all necessary data for the frontend. The JSON encoding uses appropriate flags (JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) to prevent XSS vulnerabilities.

@Aljullu Aljullu requested review from a team and dinhtungdu and removed request for a team July 21, 2025 10:15
Copy link
Contributor

github-actions bot commented Jul 21, 2025

Testing Guidelines

Hi ,

Apart from reviewing the code changes, please make sure to review the testing instructions (Guide) and verify that relevant tests (E2E, Unit, Integration, etc.) have been added or updated as needed.

Reminder: PR reviewers are required to document testing performed. This includes:

  • 🖼️ Screenshots or screen recordings.
  • 📝 List of functionality tested / steps followed.
  • 🌐 Site details (environment attributes such as hosting type, plugins, theme, store size, store age, and relevant settings).
  • 🔍 Any analysis performed, such as assessing potential impacts on environment attributes and other plugins, conducting performance profiling, or using LLM/AI-based analysis.

⚠️ Within the testing details you provide, please ensure that no sensitive information (such as API keys, passwords, user data, etc.) is included in this public issue.

@Aljullu Aljullu requested review from Aljullu and removed request for dinhtungdu July 21, 2025 13:33
Copy link
Contributor

@Aljullu Aljullu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this, @amitraj2203!

In grouped products, if a child product has a minimum quantity, it seems to be ignored. So using this code:

add_filter( 'woocommerce_quantity_input_min', function( $default, $product ) {
	if ( $product->get_id() === 110 ) {
		return 3;
	}
	return $default;
}, 10, 2 );

I can still move the quantity to be below 3:

Enregistrament.de.pantalla.a.2025-07-21.15-44-44.mp4

Also, some tests will need to be updated and I left some comments inline below. 👇

Comment on lines +370 to +376
$context['products'][ $product_id ] = array(
'id' => $product_id,
'type' => $product->get_type(),
'quantity' => 0,
'quantityConstraints' => $this->get_quantity_constraints( $product ),
'parentProductId' => null,
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code seems to be the same in the if and in the else? Could it be moved outside?

);
}

$context['currentProductId'] = $product_id;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move this before the if clause, so it's clearer it's applied in all cases. Also, I would name it productId as it's done in the blockified Add to Cart + Options block. What do you think?

Comment on lines +361 to +365
'id' => $child_product_id,
'type' => $child_product->get_type(),
'quantity' => 0,
'quantityConstraints' => $this->get_quantity_constraints( $child_product, true ),
'parentProductId' => $product_id,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Besides quantityContraints, do we need any of these other data for child products?

// Regex pattern to match the <input> element with id starting with 'quantity_'.
$pattern = '/(<input[^>]*id="quantity_[^"]*"[^>]*\/>)/';
$pattern_stepper = '/(<input[^>]*id="quantity_[^\"]*"[^>]*data-wp-on--change="actions.handleInputChange"[^>]*\/>)/';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is checking for data-wp-on--change="actions.handleInputChange" presence required?

*/
public function filter_grouped_product_quantity_column( $value, $grouped_product_child ) {
// Only wrap if stepper style is enabled and the child is purchasable and in stock.
if ( ! Features::is_enabled( 'add-to-cart-with-options-stepper-layout' ) ) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Besides the feature flag being enabled, we also need to check if the block is using the Stepper style. Because if it's using the Input style, running this filter is not needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
plugin: woocommerce Issues related to the WooCommerce Core plugin. type: community contribution
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Tab navigation inconsistency between QuantityStepper and QuantitySelector components
2 participants