Home > widget-integration > FilterHelper

FilterHelper class

Central helper service providing utility functions for the filter module.

This service acts as a unified facade for filter-related operations, delegating to specialized helper services (URL, Format, Storage, Validation) while also providing core utilities for JSON parsing, debouncing, event management, template handling, and product URL construction. It can be extended by Technical Support teams to customize filter behaviors, add shop-specific logic, or override default implementations.

Signature:

export declare class FilterHelper 

Remarks

Key responsibilities: - Event management system (on, off, emit) for filter state changes - Template resolution and customization - Product URL construction with collection/variant handling - Delegation to specialized helpers (URL, Format, Storage, Validation) - Utility functions (debounce, JSON parsing, equality checks, sorting) - Session/localStorage management - Handler wrapper system for customization hooks

The FilterHelper provides a convenient single point of access for most filter operations while maintaining separation of concerns through specialized helpers.

Example

Extend to customize URL building logic:

window.boostWidgetIntegration.extend('FilterHelper', (FilterHelper) => {
  return class CustomFilterHelper extends FilterHelper {
    buildProductDetailUrl(handle, hasCollection, currentTags) {
      // Add custom tracking parameter to all product URLs
      const baseUrl = super.buildProductDetailUrl(handle, hasCollection, currentTags);
      return baseUrl + '?utm_source=filter';
    }
  };
});

Constructors

Constructor

Modifiers

Description

(constructor)(store, appService, platformLoader, urlHelper, formatHelper, storageHelper, validationHelper, templateAPI)

Constructs a new instance of the FilterHelper class

Properties

Property

Modifiers

Type

Description

checkExistFilterOptionParam

(isShortenUrlParam?: boolean) => boolean

normalizeObject

<T extends Record<string, unknown>>(obj: T) => { [K in keyof T]: Primitive | T[K]; }

Normalizes object values by attempting to coerce string values into proper primitive types using toProperType.

toProperType

<T>(value: T) => T | Primitive

Converts string literals to their proper primitive types when possible. - "true"/"false" => boolean - "null" => null - "undefined" => undefined - numeric strings (strict decimal format) => number - otherwise returns original value

Methods

Method

Modifiers

Description

addB2BParams(queryParams, b2bConfig)

Adds B2B parameters to query params if B2B is enabled

addLocaleParam(params)

Adds locale parameter to query params if available

appendQueryParamHistory(key, value, replace, options)

Appends a value to a query parameter in the URL Used for multiple selection filters to add new values without replacing existing ones

buildProductDetailUrl(handle, hasCollection, currentTags)

Builds a product detail URL with optional collection context.

Constructs the product detail page URL, optionally including collection context in the path for better navigation and SEO. Handles locale prefixes, collection handles, and tag-based URLs. This is a key extensibility point for customizing product navigation behavior. Override to implement shop-specific URL structures, add tracking parameters, or modify collection context logic.

buildProductDetailUrlWithVariant(product, hasCollection, currentTags, variantId)

Builds a product detail URL with variant parameter.

Constructs a complete product URL including the variant query parameter when needed. Automatically appends ?variant={id} for split products or when a specific variant ID is provided. This ensures the correct variant is selected when the customer lands on the product page. Override to customize variant parameter handling or add additional query parameters.

buildQueryParams(params)

Builds a URLSearchParams object from filter API parameters

clear()

convertValueRequestStockStatus(value)

protected

Converts stock status values for API requests.

Transforms stock status filter values into boolean format for the API. Converts 'out-of-stock' to false and all other values to true. Handles both single values and arrays. Override this method to customize stock status conversion logic for shop-specific requirements.

createHandler(callback, handlerName)

Wraps a callback function to handle customization logic. Checks if custom handler functions are defined for the callback name and block type, and wraps the original callback to call them before/after. Allows overriding default handlers or injecting logic before/after calls.

debounce(fn, delay)

Creates a debounced version of a function that delays execution until after a specified time.

Useful for optimizing performance by delaying expensive operations (like API calls or DOM updates) until after rapid consecutive calls have finished. The timer resets on each new invocation. Override this method to customize debounce behavior or add logging for debugging.

deleteQueryParamHistory(key, options)

Deletes a query parameter from the URL and updates browser history Handles both shortened and full parameter names, sessionStorage cleanup, and URL schemes

deleteQueryParamsHistory(keys, options)

detectDeviceByWidth(mobileBreakpoint, tabletBreakpoint)

Detects device type by width (mobile and/or tablet portrait)

emit(event, data)

emitDynamic(key, data)

escapeCssSelector(selector)

flattenTagsToObject(array)

Flattens nested tag structure into a flat object mapping tag to displayName

formatCurrency(options)

Formats a currency value according to shop settings

formatMoney(money, format, withTrailingZeros, showCentAsSuperscript, removePriceDecimal, removeDecimalPoint)

Formats money value according to specified format options

generateCacheKey(queryParams)

Generates a cache key from query parameters

generateUuid()

Generates a unique ID

getBreakpointMobile()

Gets the mobile breakpoint from TAE configuration. Used for detecting strictly mobile devices (phones).

getBreakpointTabletPortraitMax()

Gets the tablet portrait max breakpoint from TAE configuration. Used as the default breakpoint for isMobile() — matching TAE's SSR isTabletPortraitMaxWidth() and the legacy isMobile() default (991).

getCollectionIdByHandleKey(key)

Gets collection ID by handle key

getCollectionTagFromSlugKey(key)

Gets collection tag from slug key

getCustomerId()

Gets customer ID from window object

getLocalStorage(key)

Gets a value from localStorage

getParamsHistory()

Parses URL search parameters and extracts filter params, sort, and pagination Handles both shortened and full parameter formats

getQueryParamByKey(key)

getRegisteredEvents()

getSessionId()

Gets session ID for tracking

getSessionStorage(key, fallback)

getTemplate(templateKey)

Gets a specific template by key with customization support.

Retrieves templates for rendering filter UI components, checking for customized versions in TAEAppConfig.templateParsed or TAEAppConfig.template before falling back to default templates. This is a critical customization point allowing shops to completely override widget UI rendering. Override this method to add template preprocessing, caching, or custom template resolution logic.

getTemplateByIds(widgets)

Fetches templates from API with caching support.

Retrieves templates by their IDs from the template API, with automatic localStorage caching for performance. Checks cache first before making API calls. This method is useful for dynamically loading templates that aren't included in the initial app configuration.

getUrlScheme()

hasMultiVariantPriceFormat(amountTranslation)

Checks if multi-variant price should be displayed based on translation template

hasNestedChildren(node)

Checks if a node has nested children (tags or subTags)

isBadSearchTerm(term)

isCollectionPage()

isEnterOrSpaceKeyPressed()

isEqual(value1, value2)

isInCollectionSearch()

Checks if current page is a search within collection page

isMobile(breakpoint)

Checks if device is mobile based on breakpoint. Default breakpoint is getBreakpointTabletPortraitMax() (991px), matching TAE's SSR isTabletPortraitMaxWidth() for consistent mobile/desktop layout switching.

isPageType()

protected

Checks if current page is a generic page type (not product/collection).

Determines whether the current URL is a Shopify page (e.g., About, FAQ) by checking for '/pages/' in the path. This affects URL construction logic. Override this method to customize page type detection for shop-specific structures.

isPriceAlreadyTransformed(element, dataAttribute)

Checks if price transformation has already been applied to element

isSamePrice(priceMin, priceMax, compareAtPriceMin, compareAtPriceMax)

Checks if product has same min and max prices

isSearchPage()

Checks if current page is a search page

isTagPage(currentTags)

protected

Checks if current page is a tag page.

Determines whether the current page is displaying tagged products by checking for '/tagged/' in the URL path or the presence of currentTags array. This affects how product URLs are constructed. Override this method to customize tag page detection logic for shop-specific URL structures.

isValidPriceHTML(html)

Validates if HTML contains actual price data (has digits)

isVendorPage()

Checks if current page is a vendor page

off(event, callback)

on(event, callback)

parseFilterTreeToParams(filterTree)

Parses filter tree to flat parameters object - delegates to service

processHTMLResponse(html)

Extracts and processes HTML response

removeQueryParamHistory(key, value, options)

Removes a specific value from a query parameter in the URL This is different from deleteQueryParamHistory which removes the entire parameter

removeQueryParamsHistory(params, options)

Removes specific values from multiple query parameters in the URL Handles both shortened and full parameter names with multiple URL schemes

replaceDotCommaZero(value)

Replaces trailing dot/comma and zeros from number string

rewriteUrlFromParams(data, options)

Rewrites the URL with new filter parameters, sort, and pagination Clears existing filter params and sets new ones based on provided data

safeParseJSON(json)

Safely parses JSON string with optional type guard validation.

Provides safe JSON parsing that catches exceptions and returns null on failure. Supports optional type guard function for runtime type validation. This is essential for parsing user-provided data, metadata attributes, and API responses. Override this method to add logging, custom error handling, or preprocessing of JSON strings.

safeParseJSON(json, guard)

sanitizeFilterLabel(label)

saveCollectionIdByHandle(handle, value)

Saves collection ID by handle to session storage

saveCollectionTagsSlugKey(key, value)

Saves collection tags to session storage

scrollToProduct(product)

setLocalStorage(key, value)

Sets a value in localStorage

setPaginationSession(page)

Sets the pagination page in session storage

setQueryParamHistory(key, value, replace, options)

Sets a query parameter in the URL and updates browser history Supports multiple URL schemes and shortened parameter names

setSessionStorage(key, value)

simpleMd5(input)

slugify(text)

Slugifies a text string for URL usage Delegates to FilterValidationHelper

sortArrayByKey(array, key, order)

Sorts an array by a specified key Handles numeric (for numbers) and string values with lexical comparison (for strings, including numeric-looking strings) Mixed number/string: attempts numeric if string is numeric, else lexical

sortByKey(data, key, order)

Sorts data by a specified key Works with both arrays and objects

sortObjectByKey(object, key, order)

Sorts an object by a specified key in its values

stripHtml(html)

Strips HTML tags from string (delegated to validationHelper for consistency)

toRangeValue(value)

Converts string to range value object Handles colon-separated range strings

toStringValue(value)

Converts range value to string representation Handles both object {lower, upper} and primitive values