Home > widget-integration > CartController

CartController class

Cart controller managing UI interactions, modal display, and cart operations

This controller provides extensive customization capabilities for Technical Support teams through protected extension points. All timing, selectors, translations, and behavior can be customized per-shop without modifying core code.

## Key Extension Points

### Button State Management - updateButtonState() - Customize button UI updates (text, disabled state, styling) - getButtonStateTranslations() - Override button text for different locales - getButtonSuccessResetDelay() - Control how long "Added!" shows (default: 500ms) - getButtonFailureResetDelay() - Control error state duration (default: 300ms)

### Cart Opening Behavior - shouldOpenCartAfterAdd() - Control when cart opens after add-to-cart - openCart() - Customize cart opening logic and animations - closeCart() - Customize cart closing and cleanup

### Theme Integration - getCartEnabledBodyClass() - Override body class for cart enabled state - getModalId() - Customize modal element ID - getModalOpenBodyClass() - Override body class when modal is open - getButtonTextSelectors() - Add custom theme button selectors

### Accessibility & Focus Management - setupWCAGAccessibility() - Extend WCAG compliance features - saveFocusElementBeforeCart() - Customize focus saving logic - restoreFocusAfterCart() - Customize focus restoration logic

## Common Customization Patterns

Signature:

export declare class CartController 

Example

// EXAMPLE 1: Multi-language shop with custom translations
window.boostWidgetIntegration.extend('CartController', (CartController) => {
  return class MultilingualCartController extends CartController {
    getButtonStateTranslations() {
      const locale = window.Shopify.locale || 'en';
      const translations = {
        de: {
          adding: 'Wird hinzugefügt...',
          added: 'Hinzugefügt!',
          failed: 'Fehler!',
          default: 'In den Warenkorb'
        },
        fr: {
          adding: 'Ajout...',
          added: 'Ajouté!',
          failed: 'Échec!',
          default: 'Ajouter au panier'
        }
      };
      return translations[locale] || super.getButtonStateTranslations();
    }
  };
});

// EXAMPLE 2: Premium shop with faster button feedback and custom styling
window.boostWidgetIntegration.extend('CartController', (CartController) => {
  return class PremiumCartController extends CartController {
    getButtonSuccessResetDelay() {
      return 300; // Faster than default 500ms
    }

    updateButtonState(button, state, customText) {
      super.updateButtonState(button, state, customText);

      // Add premium loading animation
      const icon = button.querySelector('.icon');
      if (state === 'adding') {
        icon?.classList.add('spinner-animate');
      } else {
        icon?.classList.remove('spinner-animate');
      }
    }
  };
});

// EXAMPLE 3: Shop that doesn't open cart for gift cards
window.boostWidgetIntegration.extend('CartController', (CartController) => {
  return class GiftCardCartController extends CartController {
    shouldOpenCartAfterAdd(params, result) {
      // Don't open cart for gift card purchases
      if (params?.productType === 'gift-card') {
        return false;
      }
      return super.shouldOpenCartAfterAdd(params, result);
    }
  };
});

// EXAMPLE 4: Shop with custom analytics tracking
window.boostWidgetIntegration.extend('CartController', (CartController) => {
  return class AnalyticsCartController extends CartController {
    async addToCart(params, button, shouldOpenCart, callback) {
      // Track before add
      this.trackAddToCartStart(params);

      try {
        const result = await super.addToCart(params, button, shouldOpenCart, callback);
        this.trackAddToCartSuccess(params);
        return result;
      } catch (error) {
        this.trackAddToCartFailure(params, error);
        throw error;
      }
    }

    trackAddToCartStart(params) {
      window.dataLayer?.push({
        event: 'add_to_cart_start',
        ecommerce: { items: [params] }
      });
    }

    trackAddToCartSuccess(params) {
      window.dataLayer?.push({
        event: 'add_to_cart',
        ecommerce: { items: [params] }
      });
    }

    trackAddToCartFailure(params, error) {
      window.dataLayer?.push({
        event: 'add_to_cart_error',
        error: error.message,
        params
      });
    }
  };
});

// EXAMPLE 5: Custom theme with different selectors
window.boostWidgetIntegration.extend('CartController', (CartController) => {
  return class CustomThemeCartController extends CartController {
    getButtonTextSelectors() {
      return [
        ...super.getButtonTextSelectors(),
        '.custom-theme-button',
        '.my-add-to-cart-btn'
      ];
    }

    getModalId() {
      return 'my-custom-cart-modal';
    }

    getCartEnabledBodyClass() {
      return 'custom-cart-enabled';
    }
  };
});

Constructors

Constructor

Modifiers

Description

(constructor)(cartService, cartSelectors, appService, wcagHelper, domHelper)

Constructs a new instance of the CartController class

Properties

Property

Modifiers

Type

Description

appService

protected

AppService

cartSelectors

protected

CartSelectors

cartService

protected

CartService

checkoutHandler

protected

(() => void) | null

closeButtonHandler

protected

(() => void) | null

domHelper

protected

DomHelper

outsideClickHandler

protected

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

state

protected

Signal<CartState>

SUBMIT_KEYS

protected

string[]

trapFocusHandlers

protected

WeakMap<Element, EventListener>

viewCartHandler

protected

(() => void) | null

wcagHelper

protected

WCAGHelper

Methods

Method

Modifiers

Description

addToCart(params, button, shouldOpenCart, callback)

Add product to cart with optional cart modal display

buildUrlWithLocalization(path)

protected

Build URL with localization prefix Protected method - override to customize URL building for specific shops

cleanupCartModal()

protected

Cleanup cart modal and event listeners Protected method - override to customize cleanup behavior

cleanupWCAGAccessibility()

protected

Cleanup WCAG event listeners Protected method - override to customize cleanup behavior

closeCart()

Hide cart modal Public method to close cart programmatically

connect()

getButtonFailureResetDelay()

protected

Get delay (ms) for resetting button text after failed add to cart Override to customize error state timing for specific shops

getButtonStateTranslations()

protected

Get button state translations Override to customize button text for different states and locales

getButtonSuccessResetDelay()

protected

Get delay (ms) for resetting button text after successful add to cart Override to customize button reset timing for specific shops

getButtonTextSelectors()

protected

Get button text selectors for cart buttons Override to use different selectors for custom themes

getCallbackDelay(type)

protected

Get callback delay for add to cart operations Protected method - override to customize callback timing

getCartActionButtonSelectors()

protected

Get cart action button selectors Override to use different button selectors for custom themes

getCartContentSelector()

protected

Get cart content selector for outside-click detection Override to use different cart content selector

getCartEnabledBodyClass()

protected

Get CSS class name for cart-enabled body Override to use different class name for specific themes

getCartItemButtonSelectors()

protected

Get cart item button selectors Override to use different button selectors for custom themes

getCartItemSelector()

protected

Get cart item selector Override to use different cart item selector for custom themes

getCartPagePath()

protected

Get cart page URL path Override to customize cart page URL for specific shops

getCheckoutUrl()

protected

Get checkout URL path Override to customize checkout URL for specific shops

getIconButtonClass()

protected

Get icon button class name Override for custom icon button styling

getModalCloseButtonSelector()

protected

Get modal close button selector for WCAG Override to use different close button selector

getModalId()

protected

Get modal ID for cart modal element Override to use different modal ID for specific themes

getModalOpenBodyClass()

protected

Get CSS class name for modal-open body state Override to use different class name for specific themes

getTranslation(key, defaultValue)

protected

Get translation text for cart UI elements Override to customize translations for specific shops/locales

getWCAGFocusableSelectors()

protected

Get WCAG focusable element selectors Override to customize focusable elements for specific themes

onlyNumbers(evt)

protected

Validate numeric input (allows only digits) Protected method - override to customize input validation

openCart()

Open cart modal Public method to show cart programmatically

outsideClickListener(element, event, callback, ignore)

protected

Handle clicks outside modal to close cart Protected method - override to customize outside-click behavior

render()

Handle context render - main render logic Protected method - override to customize render pipeline

restoreFocusAfterCart()

protected

Restore focused element after closing cart modal Protected method - override to customize focus restoration for specific themes

restoreFocusedElement()

protected

Restore previously focused element after cart modal closes Protected wrapper for WCAG utility

saveFocusElement(element)

protected

Save focused element before cart modal interaction Protected wrapper for WCAG utility

saveFocusElementBeforeCart()

protected

Save focused element before opening cart modal Protected method - override to customize focus management for specific themes

setupCartButtonEvents()

protected

Setup event listeners for cart action buttons (view cart, checkout, close) Protected method - override to customize button behavior

setupCartIcon()

protected

Setup cart icon click handler and accessibility Override to customize cart icon behavior for specific themes

setupCartItemEvents(modal)

protected

Setup event listeners for cart items (quantity, remove, etc.) Protected method - override to customize cart item interaction behavior

setupEventListeners()

protected

Setup global event listeners for cart operations Override to add custom event handlers for specific shops

setupModalClickOutside()

protected

Setup click-outside listener to close modal Protected method - override to customize click-outside behavior

setupWCAGAccessibility()

protected

Setup WCAG accessibility features for cart modal Protected method - override to customize accessibility behavior

setWindowLocation(url)

protected

Set window location (navigate to URL) Protected method - override to customize navigation behavior

Security: Only accepts relative URLs (same-origin) to prevent XSS attacks

shouldOpenCartAfterAdd(params, result)

protected

Should open cart modal after add to cart operation Protected method - override to customize cart opening behavior for specific shops

toggleCart()

Toggle cart modal visibility Public method to show/hide cart programmatically

updateButtonState(button, state, customText)

protected

Update button state (text and disabled state) Protected method - override to customize button state updates for specific shops