Home > widget-integration > FilterController

FilterController class

Main controller for managing filter functionality in collection and search pages.

This controller orchestrates all filter-related operations including: - Filter tree rendering and state management - Product list updates and pagination - Event handling for user interactions - Price transformation and currency formatting - Mobile and desktop responsive behaviors - Integration with cart, bundles, and recommendations

The class is designed to be extended by Technical Support teams for shop-specific customizations. Protected methods provide clear extension points for modifying filter behavior, product rendering, and UI interactions.

Signature:

export declare class FilterController extends Controller 

Extends: Controller

Example 1

Extend to customize price display for specific shops:

window.boostWidgetIntegration.extend('FilterController', (FilterController) => {
  return class CustomFilterController extends FilterController {
    protected async buildPriceHTML(priceMin, compareAtPriceMin, priceMax, options) {
      // Add custom price formatting for VIP customers
      const html = await super.buildPriceHTML(priceMin, compareAtPriceMin, priceMax, options);
      if (this.isVipCustomer()) {
        return html + '<span class="vip-badge">VIP Price</span>';
      }
      return html;
    }
  };
});

Example 2

Override product list rendering behavior:

window.boostWidgetIntegration.extend('FilterController', (FilterController) => {
  return class CustomFilterController extends FilterController {
    protected async handleFullPageReplace(domId, html) {
      // Add custom analytics before replacing DOM
      this.trackFilterChange();
      await super.handleFullPageReplace(domId, html);
    }
  };
});

Constructors

Properties

Property

Modifiers

Type

Description

adjustTooltipPosition

protected

(tooltipContent: any, rootElement: any) => void

Adjusts tooltip position to ensure it's visible within the viewport. Calculates and applies proper positioning for tooltip elements.

This method: - Positions tooltip relative to its trigger element - Handles edge cases when tooltip would overflow viewport - Supports tooltips within slick carousel slides - Applies responsive positioning based on available space

appService

protected

AppService

cartAPI

protected

CartAPI

cartController

protected

CartController

cartSelectors

protected

CartSelectors

combinedProductListingsService

protected

CombinedProductListingsService

document

protected

readonly

HTMLElement

The active DOM context for filter operations.

This document reference is set during filter initialization and can be different from the global document when working with specific DOM contexts, multiple filter instances, or when the filter is rendered in isolated containers.

domHelper

protected

DomHelper

filterHandler

protected

FilterHandler

filterHelper

protected

FilterHelper

filterRender

protected

FilterRender

filterSearchPageController

protected

FilterSearchPageController

filterService

protected

FilterService

filterStickyController

protected

StickyController

filterStore

protected

FilterStore

filterTranslationService

protected

FilterTranslationService

getProductCountTranslationConfig

(position: any, totalProduct: any) => { element: Element | null; key: string; fallback: string; }

{import('./index.d').getProductCountTranslationConfig}

handleButtonClick

(quantityInput: any, progressBarContainer: any, decreaseButton: any, quantityStep: any, variantId: any, operation: any) => (event: any) => Promise<void>

handleClickOutside

(rootElm: any, callback: any) => () => void

Sets up a click outside handler for an element. Executes a callback when a click occurs outside the specified root element.

Automatically removes the event listener after the first outside click is detected, preventing memory leaks and ensuring one-time use behavior.

handleMouseLeave

(swatch: any, productItem: any, images: any) => void

Handles mouse leave event for product swatches. Resets swatch selection and restores default product images when mouse leaves the swatch area.

Respects the global flag window.boostSDKeepVariantOnHoverOutside which allows variant selections to persist even after hovering outside.

handlePaginationLoadMoreButtons

(currentPage: any) => void

handleVolumeBundleClick

(target: HTMLElement) => void

quickAddToCartController

protected

QuickAddToCartController

quickViewController

protected

QuickViewController

registerSwatchOptionEvent

(event: any, productItem: any, swatch: any, option: any, options_with_values: any, images: any, defaultImages: any) => void

Registers event listeners for swatch option interactions. Sets up click, hover, and keyboard events for individual swatch options.

This method handles: - Click or hover events to change product variant - Keyboard navigation (Enter/Space keys) for accessibility - Outside click detection to persist or reset variant selection - Product image updates based on variant selection

setUniformProductImageHeight

() => void

tooltipHelper

protected

TooltipHelper

updateTextContent

({ element, key, fallback }: { element: any; key: any; fallback: any; }, translationData: any) => void

Methods

Method

Modifiers

Description

addSwatchTooltipScrollHandler(tooltipContent)

protected

Adds scroll event handler to hide tooltip when page scrolls. Attaches a scroll listener that hides the tooltip and auto-removes itself.

This method: - Creates a stable handler reference for proper cleanup - Hides tooltip on scroll event - Auto-removes the listener after first trigger - Prevents duplicate listeners on the same tooltip

appIntegration()

protected

Executes third-party app integrations for the filter. Triggers integration callbacks for external apps and custom scripts.

This method is an extension hook that allows third-party apps to integrate with the filter system by executing registered integration callbacks.

applyColorToSwatch(label, colorCodes)

protected

Applies color styling to a swatch element. Handles single colors and two-color gradients.

applySwatchSettings(container, options_with_values, swatch_settings)

protected

Applies custom swatch settings from admin configuration to product items. Updates swatch displays with custom colors, images, and text based on settings.

This method processes swatch options and applies admin-configured settings including: - Custom text labels for variant options - Custom color codes (single or gradient) - Custom images for swatches - Mixed color and image displays

attachEventListeners(dom)

protected

Attaches event listeners to the new DOM

bindUiFormatCurrencyForRangeSlider(container)

Binds currency formatting to range slider UI elements. Updates the currency unit display for price range sliders based on shop settings.

Queries all range slider unit elements and replaces their content with the formatted money symbol (e.g., "$", "€", "£", "₫") from the shop's money format. Respects the showCurrencyCodes setting to use the appropriate format.

buildPriceHTML(priceMin, compareAtPriceMin, priceMax, options)

protected

Builds formatted price HTML for product items

calculateSaleInfo(prices)

protected

Calculates sale information (is on sale, sale percentage, sale amount)

cleanupVideoLazyLoading()

protected

Cleans up video lazy loading resources to prevent memory leaks. Should be called when the controller is destroyed or when doing full replacements.

collapseMobileBtn(action, target)

Handles mobile filter button collapse/expand behavior Manages UI state transitions for mobile filter tree styles

connect(config)

Connects and initializes the filter controller with the provided configuration. This is the primary entry point for setting up the filter system.

Sets up the filter state with configuration and initializes all core functionality including event listeners, UI components, and filter tree rendering.

debugVideoLazyLoad()

protected

Helper method for debugging video lazy loading. Only active when enableVideoDebug() returns true.

enableVideoDebug()

protected

Debug helper for video detection. Only enabled when explicitly overridden in shop-specific extensions through window.boostWidgetIntegration.extend().

fetchInCollectionSearch(urlParams, inputElement)

protected

Fetches and updates products based on in-collection search input. Triggers search when user types in the collection search box.

This method: - Resets pagination to page 1 - Updates URL parameters with search query - Disables input during fetch to prevent concurrent requests - Fetches filtered results from the API - Dispatches analytics event for search - Re-enables input after completion

filterOptionCollapse(action, target)

Toggles the collapse state of a filter option Manages collapse/expand behavior for both mobile and desktop layouts

getEnabledSwatches()

Retrieves the list of enabled product swatches from theme settings. Returns an array of enabled swatch configurations (swatches.1, swatches.2, swatches.3).

Checks theme settings for up to 3 swatch slots and returns only those that are enabled, preserving their configuration including display type, option name, etc.

getFilterOptionById(id)

protected

Gets a filter option by its ID from the filter tree state

getFilterOptionToggleState(currentAction, options)

protected

Gets the toggled state for a filter option Updates target elements and toggles aria-expanded attributes

getPaginationType()

protected

handleBulkQuantity()

handleColorImageSwatch(label, swatchObj)

protected

Handles color and image combined swatch display. Applies custom images with optional color backgrounds or color gradients.

handleExceededPage()

handleFetchFilter(addition)

protected

Fetches filter results from the API and updates the DOM.

handleFilterTree()

handleForceRenderChange()

handleFullPageReplace(domId, html)

protected

Handles full page replacement with new filter results Handles mobile filter tree state preservation directly

handleHistoryParams()

Sets up browser history navigation handling Listens for popstate events (back/forward navigation) and updates the filter state accordingly

handleInCollectionSearch(_dom)

protected

Sets up in-collection search functionality. Initializes search input behavior including debounced search and clear button.

This method: - Sets up debounced keyup listener on search input (default 500ms delay) - Handles search query URL parameter updates - Manages input focus and cursor position on re-render - Sets up clear button click handler - Ensures input remains in viewport when focusing

handleInCollectionSearchFilter()

protected

handlePaginationInfiniteScroll()

handleProductImageSwatch(label, swatchObj)

protected

Handles product image-based swatch display. Applies custom images or colors to product image swatches.

handleProductListAppend(html, behavior)

protected

Handles appending/prepending product items to the product list

handleProductListResponsive()

Handles responsive behavior for product list layout. Adjusts product grid columns based on viewport size and view mode (grid/list).

This method: - Listens for window resize events - Detects current view mode (grid or list) - Applies appropriate column classes for mobile/desktop - Handles grid column count based on theme settings - Manages list view layout switching

handleProductSwatches()

Initializes and manages product variant swatches on product items. Handles swatch interactions, variant image updates, and hover behaviors.

Sets up swatch functionality including: - Detecting enabled swatch configurations (up to 3 swatch types) - Registering click and hover event listeners on swatch options - Updating product images when variants are selected - Managing selected state UI - Handling keyboard navigation (Enter/Space keys) - Outside click handling to preserve/reset variant selection

handleQuantityChange(variantId, quantity)

handleQuantityInput(quantityInput, progressBarContainer, minQuantity, variantId)

handleResetFilter()

protected

Handles filter reset operation.

Resets all active filters and updates the DOM with the cleared filter state. Override to add custom reset behavior.

handleScrollRestore()

Handles scroll position restoration when returning to a product list. Restores scroll to previously viewed product when navigating back from product detail page.

This method: - Disables browser's automatic scroll restoration - Checks for stored product ID in session storage - Validates the product is in the current collection - Waits for product images to load (for auto-height layouts) - Scrolls to the previously viewed product - Cleans up stored values after restoration - Handles iOS page cache restoration (pageshow event)

handleSwatchOption(params)

protected

Handles swatch option selection and updates product images. Manages variant image changes and selected state when user interacts with swatches.

This method: - Identifies the variant option from the swatch type - Updates product images based on variant selection - Handles cases where variants have no specific images - Manages selected label state (visual indicator) - Falls back to default images when variant has no image

handleTextSwatch(label, tooltip, swatchObj)

protected

Handles text-based swatch display. Updates label and tooltip text content with custom text from settings.

handleTooltip()

protected

Initializes tooltip functionality for product items.

Sets up mouseenter/mouseleave event listeners to show/hide tooltips and adjusts their positioning.

hideLoadingIcon()

protected

Hides the filter loading icon

init()

Initializes all core filter functionality. Called automatically by connect() - should not be called directly in most cases.

Orchestrates the initialization sequence including: - Collection ID saving and validation - Exceeded page handling - Filter tree setup - Core UI components (search, pagination, swatches) - Event system registration - Browser history handling - Legacy module compatibility

initCurrencyForFilterPrice()

Initializes currency formatting for price filter options. Sets the money format value on price and variant price filter options.

Determines whether to use money format with currency codes (e.g., "$10.00 USD") or without (e.g., "$10.00") based on theme settings, then applies the formatted value to price-type filter options.

initEventLineners()

Initializes all event listeners for the filter system. Sets up handlers for user interactions, filter changes, and UI updates.

Registers handlers for: - Filter tree interactions (collapse, apply, reset, clear) - Product interactions (add to cart, quick view, quick add) - Toolbar actions (sort, pagination, view mode, product limit) - Mobile filter UI (show/hide, back navigation) - Desktop filter UI (toggle, sticky behavior) - Bundle interactions (embedded, volume) - Search and state management

initLazyVideoLoading()

protected

Initializes lazy loading for video elements with data-src attributes. Uses IntersectionObserver to load videos when they become visible, improving LCP performance.

initLegacyModule()

Initializes legacy modules for backward compatibility. Sets up dynamic bundles and volume bundles using the legacy API.

This method bridges the gap between the new filter controller architecture and older bundle implementations that haven't been fully refactored yet.

initPageLimit()

Initializes pagination limit settings from local storage or admin defaults. Handles the products-per-page limit for the filter and manages persistence.

This method: - Retrieves saved limit from local storage or uses admin default - Sets the limit in filter context for API calls - Saves both admin default and current limit for comparison - Initializes pagination session with current page

initSwatchTooltipScrollHandler(container)

protected

Initializes scroll handlers for swatch tooltips. Attaches scroll event listeners to hide tooltips when page scrolls.

This method: - Iterates through all swatch options in the container - Prevents duplicate listeners using WeakSet tracking - Attaches touchstart and click events to trigger scroll handler - Ensures tooltips hide when user scrolls the page

isBackgroundImageEmpty(label)

protected

Checks if an element has an empty background image. Verifies both inline and computed background image styles.

isTabletPortraitMaxWidth()

protected

loadVideoSources(video)

protected

Loads video sources by converting data-src to src attributes. Manages loading states and auto-plays video when ready.

manageBodyScrollClass()

protected

Manages body scroll class based on filter tree visibility

playVideoSafely(video)

protected

processPaginatingAction(newPage, behavior)

refreshStickyFilter()

protected

removeUIAnimation()

Removes CSS animation classes from elements to enable proper positioning. Strips 'animate--slide-in' and 'animation--fade-in' classes that may interfere with fixed positioning or filter functionality.

This method is necessary because some themes apply animation classes that can cause layout issues with fixed-position filter elements or sticky behaviors.

renderFilterTreeOnStateChanged()

renderRecommendationForSearchPage()

protected

Renders product recommendations on search result pages. Triggers recommendation widget rendering for search pages with results.

This method is an integration hook that delegates to the dynamicBundle module to render product recommendations based on search context.

renderTierDiscountBundleForSearchPage()

protected

Shows or hides the tiered bundle on the search page based on the latest API response.

Reads dynamicBundles from filterStore (updated after every filter/sort/pagination request) and drives the tier-discount container accordingly: - Tiered bundle present → dispatch boost-sd-tier-discount-search-reinitialize so the helper re-renders the widget with current data. - No tiered bundle → reset and clear the container so stale content is removed.

renderVolumeBundleForSearchPage()

protected

Renders volume bundle widgets on search result pages. Dynamically imports and initializes volume bundle rendering for search context.

This method uses dynamic import (code splitting) to load the volume-bundle module only when needed, reducing initial bundle size.

setInfiniteScrollLoading(_isLoading)

protected

setProductImageToDefault(productItem, images)

Resets product images to their default state. Restores the original product images when a swatch selection is cleared or on mouse leave.

Handles both single and dual image displays (for hover effects) and includes optimizations to prevent flickering by checking if the current image differs from the target image before updating.

setupCoreUI()

Sets up and initializes all core UI components for the filter system. Handles both initial render and post-filter-update UI synchronization.

Initializes: - SEO meta tags for search engines - Currency formatting for price filters - Filter option collapse states - Product list responsive behavior - Product price display and transformations - Product swatches and variant selection - Image height uniformity - Tooltips and animations - Scroll restoration - Bulk quantity controls (if enabled) - Search result tabs (for search pages) - Infinite scroll pagination (if enabled)

setupDocumentClickEvent()

Sets up click event listeners on the filter document context. Delegates all click handling within the filter scope to the FilterHandler.

This method uses event delegation to efficiently handle all clicks within the filter context, including filter options, buttons, links, and interactive elements.

setupKeydownEvent()

Sets up keyboard event listeners for filter interactions. Handles keyboard navigation for sort controls, view options, limit lists, and bundles.

Supports keyboard accessibility by responding to standard keys (Enter, Space, Arrow keys). Stores the key code in filter state for use by other handlers.

setupOutSideClickEvent()

Sets up global click event listeners to handle clicks outside filter components. Manages closing behaviors for dropdowns, filter options, and popups when clicking outside.

Handles: - Closing horizontal filter options when clicking outside - Closing sort dropdowns - Closing limit list dropdowns - Closing mini popups

setupScrollToTopButton()

Sets up the scroll-to-top button behavior. Shows or hides the button based on scroll position with a 300px threshold.

The button becomes visible when the user scrolls down more than 300 pixels and is hidden when scrolling back to the top. Uses debouncing (200ms) for performance optimization.

showLoadingIcon()

Shows the filter loading icon

transformFilterTreeHTML(html)

Transforms HTML response to apply filter tree styles based on current state Handles mobile/desktop toggle button states and layout styles

transformProductPrice()

protected

Transforms product prices in the DOM using IntersectionObserver for performance Handles multi-variant pricing, sale prices, and currency formatting

updateFilterDOM(domId, html, behavior)

Updates DOM with filter results Handles different update behaviors: replace, append (more), or prepend (previous)

updateInfiniteScrollState()

protected

Updates infinite scroll loading state

updateProductCount(limit, totalProduct)