Home > widget-integration > CartDrawerRecommendationController

CartDrawerRecommendationController class

Controller for managing recommendation widget interactions within the cart drawer.

NOTE: This controller does NOT extend RecommendationWidgetController to avoid circular dependency (RecommendationModule imports CartModule). Instead, it implements its own formatPrice() method using the same logic as the base controller.

This controller handles user interactions with recommendation products that are rendered by the backend cart template. The template renders the recommendation widget using data from CartService.getCartDrawerRecommendationData().

## Key Responsibilities - Handles "Add to Cart" button clicks from recommendation products - Manages native CSS/JS carousel (not Slick) for recommendation products - Dispatches cart updated events after adding products - Manages event listeners for cart drawer lifecycle

## Extension Points - getAddToCartButtonSelector() - Customize the Add to Cart button selector - getRecommendationContainerSelector() - Customize the recommendation container selector - handleAddToCart() - Customize add to cart behavior - afterCartDrawerAddToCart() - Add custom post-add-to-cart logic - getSlidesPerView() - Customize number of slides per view based on cart style - getHighlightDuration() - Customize success/error message display duration - getErrorMessage() - Customize error message extraction for shop-specific errors - formatPrice() - Customize price formatting for variant price updates - getAddingButtonText() / getAddedButtonText() / getFailedButtonText() / getDefaultAddButtonText() / getSuccessMessageText() - Customize button and message strings for localization

Signature:

export declare class CartDrawerRecommendationController 

Example

Extend to customize add to cart behavior:

window.boostWidgetIntegration.extend('CartDrawerRecommendationController', (Base) => {
  return class CustomCartDrawerRec extends Base {
    async handleAddToCart(productId, variantId) {
      // Custom logic before adding to cart
      await super.handleAddToCart(productId, variantId);
      // Custom logic after adding to cart
    }
  };
});

Constructors

Constructor

Modifiers

Description

(constructor)(appService, cartAPI, cartDrawerRecommendationService, constants)

Constructs a new instance of the CartDrawerRecommendationController class

Properties

Property

Modifiers

Type

Description

appService

protected

AppService

boundChangeHandler

protected

((event: Event) => void) | null

boundClickHandler

protected

((event: Event) => void) | null

boundDragStartHandler

protected

((event: Event) => void) | null

boundResizeHandler

protected

(() => void) | null

cartAPI

protected

CartAPI

cartClosedHandler

protected

readonly

() => void

cartDrawerRecommendationService

protected

CartDrawerRecommendationService

cartOpenedHandler

protected

readonly

() => void

constants

protected

CartDrawerRecommendationConstants

dragState

protected

DragState

handleNativeDragEnd

protected

() => void

Handle mouse drag end.

handleNativeDragMove

protected

(event: MouseEvent) => void

Handle mouse drag move.

handleNativeDragStart

protected

(event: MouseEvent) => void

Handle mouse drag start.

handleNativeNextClick

protected

() => void

Handle click on next button. Slides by the number of products per row (slidesPerView).

handleNativePrevClick

protected

() => void

Handle click on previous button. Slides by the number of products per row (slidesPerView).

handleNativeTouchEnd

protected

() => void

Handle touch end.

handleNativeTouchMove

protected

(event: TouchEvent) => void

Handle touch move.

handleNativeTouchStart

protected

(event: TouchEvent) => void

Handle touch start.

hasInitialized

readonly

boolean

Whether the controller has been initialized with click handlers.

isInitialized

protected

boolean

nativeCarouselState

protected

CarouselState | null

Methods

Method

Modifiers

Description

afterCartDrawerAddToCart(productId, variantId)

protected

Called after a product is successfully added to cart from cart drawer. Override to add custom post-add-to-cart logic such as analytics tracking, notification display, or triggering shop-specific side effects.

applyLayoutModifier()

protected

Apply or remove the two-columns layout modifier class on the recommendation container. This class enables CSS grid styling for the two-columns layout on desktop. On mobile/tablet the modifier is removed so the carousel layout takes effect.

Called on cart open, after re-fetch render, and on window resize.

applySliderDisabled()

protected

Add the disabled class to the slider element when carousel is not initialized. This signals via CSS that the slider navigation and scroll behavior are inactive.

areAllProductsHidden()

protected

Check if all products in the recommendation widget are hidden. Checks both the synchronous data-rcu-hidden attribute (set immediately by ) and display:none (set after fade animation).

clearErrorMessage(productItem)

protected

Clear error message from a recommendation item.

clearSuccessMessage(productItem)

protected

Clear success message from a recommendation item.

destroy()

Full cleanup of all event listeners and resources. Removes click/change handlers, cart drawer open/close listeners, and destroys the native carousel.

Call this when the module is being destroyed and the controller should no longer respond to any events.

destroyNativeCarousel()

protected

Destroy the native carousel and clean up resources.

finalizeNativeDrag()

protected

Finalize drag interaction and snap to nearest slide.

formatPrice(price, showCurrencyCodes)

Formats a price value according to shop settings and theme configuration.

This method implements the same logic as RecommendationWidgetController.formatPrice() but is duplicated here to avoid circular dependency issues.

formatPriceIfNeeded(price, showCurrencyCodes)

protected

Format price if it appears to be a raw number string. If the price already contains currency symbols or non-numeric characters, it's considered already formatted and returned as-is.

Uses the local formatPrice() method for consistent formatting.

getAddedButtonText()

protected

Get the button text displayed after successfully adding a product to cart. Override this method to customize success button text for localization or shop-specific messaging.

getAddingButtonText()

protected

Get the button text displayed while adding a product to cart. Override this method to customize button text for localization or shop-specific messaging.

getAddToCartButtonSelector()

protected

Get the CSS selector for Add to Cart buttons in cart drawer recommendations. Override this method to use a different button selector.

getAddToCartQuantity(productItem)

protected

Get the quantity to add when clicking the Add to Cart button. Override to implement quantity pickers or per-product custom quantities.

getBoundedNativeTranslateX(translateX)

protected

Get bounded translateX value within carousel limits.

getButtonResetDelay()

protected

Get the delay in milliseconds before resetting the Add to Cart button text after success or error. Override to adjust how long the success/error button state remains visible before returning to default.

getCartDrawerSelector()

protected

Get the CSS selector for the cart drawer modal. Override this method if your theme uses a different cart drawer structure.

getCurrentNativeTranslateX()

protected

Get the current translateX value from the container element.

getDefaultAddButtonText()

protected

Get the default button text for the Add to Cart button. Override this method to customize default button text for localization or shop-specific messaging.

getErrorMessage(error)

protected

Extract a user-friendly error message from an error. Override to customize error messages for shop-specific error patterns or to add localization support.

getFailedButtonText()

protected

Get the button text displayed when adding a product to cart fails. Override this method to customize error button text for localization or shop-specific messaging.

getHighlightDuration()

protected

Get highlight duration in milliseconds for success/error states. Override to adjust how long success and error messages remain visible.

getImageWidth()

protected

Get the image width for recommendation product images. Checks widget design settings first, then falls back to default.

Override this method to customize image width calculation.

getNextButtonSelector()

protected

Get the CSS selector for the next button.

getPrevButtonSelector()

protected

Get the CSS selector for the previous button.

getProductVariantCount(productItem)

protected

Get the number of variants for a product from its DOM element. Checks data attribute or variant selector options.

getRecommendationContainerSelector()

protected

Get the CSS selector for the recommendation container in cart drawer. Override this method to use a different container selector.

getSliderContainerSelector()

protected

Get the CSS selector for the slider track (container of slides).

getSliderSelector()

protected

Get the CSS selector for the slider container. Override this method to use a different slider selector.

getSlideSelector()

protected

Get the CSS selector for individual slides.

getSlidesPerView()

protected

Get the number of slides to show per view based on cart style. Uses numberOfProductPerRowSlideCart for 'side' cart style, and numberOfProductPerRowPopupCart for 'popup'/'modal' cart style.

Override this method to customize slides per view calculation.

getSuccessMessageText()

protected

Get the success message text displayed after adding a product to cart. Override this method to customize success message for localization or shop-specific messaging.

getVariantSelectSelector()

protected

Get the CSS selector for variant select dropdowns.

getWidgetDesignSettings(container)

protected

Extract widget design settings from the recommendation container data attributes or from the TAE config (same approach as other recommendation widgets like volume-bundle).

handleAddToCart(productId, variantId, buttonElement)

protected

Handles adding a product to cart from recommendation widget.

Optimization: Does NOT re-fetch recommendation API after add to cart. - If product has 0-1 variants: hides the product from widget (DOM only) - If all products are hidden: re-fetches API to get new recommendations - If product has 2+ variants: keeps it visible for user to add other variants

hideEmptyRecommendationBlock()

protected

Hide the recommendation block when it contains no product items. Prevents showing an empty/broken layout in the cart drawer.

hideProductFromWidget(productItem)

protected

Hide a product from the recommendation widget. Uses CSS display:none for immediate visual feedback.

hideRecommendationWidget(container)

protected

Hide the entire recommendation widget when no products available.

initNativeCarousel()

protected

Initialize the native CSS/JS carousel for recommendation products. Sets up slide dimensions, navigation buttons, and initial position.

isColumnLayout()

protected

Determine whether the current layout is the two-columns grid layout.

Returns true when the viewport is desktop (> 991px) and the cart is configured with cartStyle: 'side' and sideLayout: 'two-columns'. On mobile/tablet this always returns false since the two-columns layout is desktop-only.

refetchAndRenderRecommendations()

protected

Re-fetch recommendation data and re-render the widget. Called when all products have been hidden after add-to-cart actions.

removeCartDrawerEventListeners()

protected

Removes cart drawer event listeners.

removeClickHandlers()

protected

Removes click and change handlers from the cart drawer. Called when the cart drawer is closed.

removeResizeHandler()

protected

Remove the resize handler.

removeSliderDisabled()

protected

Remove the disabled class from the slider element when carousel is initialized.

removeVariantSelectHandlers()

protected

Removes the delegated change handler for variant selects. Called when the cart drawer is closed.

renderRecommendationWidget(container, data)

protected

Render the recommendation widget with new data. Override this method to customize rendering.

Returns a Promise that resolves when the DOM update is complete. The consumer listening to 'boost-sd-rcu-refetch' should dispatch 'boost-sd-rcu-render-complete' after finishing the DOM update.

setupCartDrawerEventListeners()

protected

Sets up event listeners for cart drawer open/close events.

setupClickHandlers()

protected

Sets up click handlers for Add to Cart buttons in recommendations. Called when the cart drawer is opened.

setupNativeCarouselNavigation(sliderElement)

protected

Setup click handlers for carousel navigation buttons.

setupNativeDragHandlers(sliderElement)

protected

Setup drag and touch handlers for carousel swipe functionality.

setupResizeHandler()

protected

Setup a debounced resize handler that reinitializes the carousel when the window size changes (e.g., viewport rotation, drawer width change).

setupVariantSelectHandlers(cartDrawer)

protected

Setup change handlers for variant select dropdowns. Uses event delegation on the cart drawer container to avoid memory leaks. Updates the product item's data-variant-id when variant selection changes.

shouldInitCarousel()

protected

Determine whether the native carousel should be initialized.

Returns false when the viewport is desktop (> 991px) and the cart is configured with cartStyle: 'side' and sideLayout: 'two-columns'. In that layout the products are rendered in a static two-column grid and no slider/carousel is needed. On mobile/tablet the carousel still initializes normally.

Override this method to add custom conditions for carousel initialization.

showErrorMessage(productItem, message)

protected

Show an error message on a recommendation item.

showSuccessMessage(productItem)

protected

Show a success message in the recommendation widget after adding to cart.

updateCarouselAfterProductRemoval()

protected

Update carousel state after a product has been removed. Recalculates slide positions and updates navigation.

updateNativeCarouselButtons()

protected

Update carousel navigation button visibility/state. Hides prev button at start, hides next button at end.

updateNativeCarouselPosition()

protected

Update the carousel position by translating the container.

updateProductImage(productItem, imageUrl)

protected

Update the product image when variant changes. Override to customize image update behavior.

updateProductPrice(productItem, price)

protected

Update the product price when variant changes. Override to customize price update behavior.

Uses the local formatPrice() method for consistent price formatting across all recommendation widgets, including currency code display based on cart settings.