Home
Wiki
Home
Wiki
  1. Javascript
  • Back to home
  • 1. Themes
  • Vs Code
    • Getting Started
  • Kitchenware
    • Layout
      • New Layout
      • Legacy Layout
    • Components
      • Announcement
      • Banner Carousel
      • Banner With Products Carousel
      • Blog Category List
      • Blog List
      • Brand List
      • Brands Carousel
      • Breadcrumb
      • Call To Action
      • Cart
      • Categories List
      • Change Password
      • Checkout
      • Cookie Manager
      • Filter list
      • Footer
      • Forgot Password
      • Form
      • Hero Carousel
      • Icon Block
      • Invitation
      • Last Visited Products
      • Layout
      • Login
      • Map
      • Nav Bar
      • Offer
      • Product Attachments
      • Product Attributes
      • Product Documentation
      • Product Expected
      • Product Modal
      • Products Block
      • Products Carousel
      • Product Single
      • Profile
      • Quote
      • Register
      • Related Products
      • Search
      • Stores
      • Subscribe Newsletter
      • Text with Image
      • Top Bar
      • Video
    • Reusables
      • Getting Started
    • Assets
      • Getting Started
    • SDK
      • Products
        • _findProductsByCategory
        • _findProductsByIds
        • _findProductsByTitle
        • _findProductsByFilter
        • _findProductsByCriteria
        • _findProductsAndCalculate
        • _findProductsThenCalculate
        • _getProductAttributeSet
        • _setLastVisited
      • Categories
        • _findCategoryTreeById
        • _findCategoriesByIds
        • _findCategoryByAlias
        • _findCategoryTreeByAlias
        • _getCategoryContent
      • Collections
        • _getCollectionContent
        • _findCollectionsByIds
        • _findCollectionsByIdsThenCalculate
      • Brands
        • _getBrandContent
        • _findBrandsByIds
      • Cart
        • _addToCartMulti
        • _addToCart
        • _setCart
        • _clearCart
        • _setCartListener
        • _removeFromCart
        • _calculateCart
      • Checkout
        • _startCheckout
        • _updateCheckout
        • _completeCheckout
      • Shopping Lists
        • _getShoppingLists
        • _updateShoppingList
        • _createShoppingList
        • _deleteShoppingList
        • _getShoppingListByAlias
      • Navigation
        • _getFooterMenu
        • _getHeaderMenu
      • Users
        • _getUserById
      • Utils
        • _calculateCurrency
        • _getCurrencySymbol
        • _getCulture
        • _subscribeToNewsletter
        • _findUnitsByIds
  • Noir
    • 0. Introduction
    • 1. Structure
      • Overview
      • LayoutA.liquid
      • ComponentsList.liquid
      • Metas.liquid
      • CssVariables.liquid
      • Json.liquid
      • GoogleTagManager.liquid
      • StagingButton.liquid
    • 2. Components
      • Overview
      • Announcement
      • BannerCarousel
      • BlogCategoryList
      • BlogList
      • BrandList
      • Breadcrumb
      • Cart
      • CategoriesList
      • ChangePassword
      • Checkout
      • CookieManager
      • FilterList
      • Footer
      • ForgotPassword
      • Form
      • IconBlock
      • Invitation
      • LastVisitedProducts
      • Login
      • Map
      • NavBar
      • ProductAttachments
      • ProductAttributes
      • ProductComparison
      • ProductDocumentation
      • ProductMixList
      • ProductsBlock
      • ProductsCarousel
      • ProductSingle
      • Profile
      • Register
      • RelatedProducts
      • SingleBlog
      • Stores
      • TextWithImage
      • ThankYouPage
      • TopBar
      • Wishlist
    • 3. Reusables
      • Overview
      • Addresses
      • BillingRetail
      • AddressForm
      • AnnouncementModal
      • BackToTop
      • Company
      • General
      • Login
      • LoginModal
      • Orders
      • Payment
      • ProductAttachments
      • ProductAttributes
      • ProductComparisonButton
      • ProductComparisonFloatingButton
      • ProductGridItem
      • ProductListItem
      • ShoppingListsButton
      • ProductModal
      • ProfileInfo
      • PromptModal
      • Register
      • Shipping
      • ShoppingLists
      • ShoppingListsNavbar
      • Toast
      • Users
      • VariantContent
      • WishlistButton
      • Services
    • 4. Assets
      • Fonts
      • Images
      • Templates
      • Javascript
        • Overview
        • theme.js
      • Css / Scss
        • Overview
        • ThemeClasses
    • 5. SDK
      • Overview
      • LiquidGlobals
      • ServicesSDK
  1. Javascript

theme.js

Purpose#

This page documents Assets/js/theme.js.
theme.js is the theme’s main client-side boot file. It is responsible for:
Global initialization on DOMContentLoaded
Defining shared utilities (cookies, IntersectionObserver helpers, etc.)
Defining Google Analytics (GA4) helpers and mappings
Wiring or supporting global Alpine stores by providing shared helpers/services
It is loaded once (from the layout) and is expected to be safe to run on every page.

What theme.js contains#

Global initialization (DOMContentLoaded)#

theme.js registers a DOMContentLoaded handler that performs page-level bootstrapping.

Main min-height calculation#

It calculates a CSS variable --min-height on <main> so the footer is pushed to the bottom.
Inputs:
header.offsetHeight
footer.offsetHeight
window.innerHeight
Behavior:
Sets main.style.setProperty('--min-height', '<px>')
Recalculates on window.resize

Cart token initialization#

If localStorage.cartToken does not exist, it is created.
Two paths:
Authenticated user:
Calls GET /api/cart/user and stores the returned token.
Guest user:
Generates a token using servicesreusabledefault.uuidv4().
Side effects:
Writes localStorage.cartToken
Writes cookie cartToken via setCookie('cartToken', ...)
Dependencies:
userAuthenticated global flag (provided by the rendered page/layout)
axios
servicesreusabledefault.getAxiosResponse(...)
servicesreusabledefault.uuidv4()

Floating compare button logic#

When window.showProductComparison is enabled, theme.js updates the floating compare button.
It reads comparison state from the cookie:
comparisonData (JSON array)
It reacts to:
storage events with key comparisonSync
Custom event comparisonListUpdated
UI behavior:
Sets button display to flex when there are items
Updates the numeric count element

Cookie management helpers#

theme.js defines small cookie helpers:
setCookie(name, value, days = 31)
sets a cookie with an expiry
setSessionCookie(name, value)
sets a session cookie
getCookie(name)
returns a cookie value as string
These helpers are widely reused by other scripts and services.

Google Analytics 4 (GA4) helpers#

theme.js contains a large GA4 helper section.
Key pieces:
GoogleAnalyticsActions constants
ga4Mapping mapping object
getCurrencyCode() utility (reads _currency cookie; defaults to eur)

IntersectionObserver helper: elementInView(...)#

elementInView(targets, onInView, options) wraps an IntersectionObserver.
Parameters:
targets: element, selector string, or array of elements
onInView: callback
options:
root, rootMargin, threshold
once (default true)
Behavior:
Falls back to calling onInView() immediately when IntersectionObserver is not supported.

Item mapping helpers#

Helpers prepare items for GA events:
mapItemsToGAFormat(items)
preparePropertiesForGA(items, listName, listIndex)
batchItems(items)
calculateTotalValue(items)
These functions:
Add position indices
Convert internal item shapes into GA4 item properties
Support batching with GOOGLE_ANALYTICS_BATCH_SIZE

Alpine stores initialized in theme.js#

theme.js initializes multiple global Alpine stores during document.addEventListener('alpine:init', ...).
These stores are part of the theme’s shared runtime “contract” and are referenced from Liquid templates via $store.<name>.

profile#

Purpose:
Holds lightweight state related to Profile tabs.
Key fields:
tabChanged (boolean)

sharedAddresses#

Purpose:
Shared state for addresses/invoices forms across different areas.
Key fields:
validAddresses[]
addresses[]
invoices[]
updateShippingAddresses (boolean)
runToast
Key methods:
updateValidAddress(index, isValid)
updateAddress(index, updatedAddress, isB2bCustomer = false)
updateInvoice(index, updatedInvoice)

cart#

Purpose:
Client-side mirror of cart summary data, backed by localStorage.cartData.
Optional “added to cart” popup behavior.
Key fields:
items[]
netValueText, vatValueText, finalPriceText
popupProducts
Key methods:
init() (loads from storage and listens to storage events)
loadFromStorage()
update(cartData, addedProductsArray = [], showPopUp = false)
showPopup(products)
setPopupHovering(isHovering)
clearPopupTimeout()
Notes:
showPopup(...) closes $store.productModal before showing the popup.

toast#

Purpose:
Central toast queue used across the entire theme.
Key fields:
messages[]
Key methods:
add(message, iconClass = null, type = 'info', keepAlive = false, extraHtml = null, extraHtmlIndex = null)
remove(id)
removeAll()
Notes:
Auto-dismisses messages after 5000ms when keepAlive is false.

modal#

Purpose:
Central modal state (used by prompt/invite/manage flows).
Key fields:
current
visible
errors
shouldReinitialize
Key methods:
open(config)
close()
Notes:
close() also clears toasts if any exist.

viewedAnnouncements#

Purpose:
Tracks which announcements have been viewed.
Storage strategy:
Guests: session cookie viewed_announcements
Authenticated users: localStorage.viewedAnnouncements
Key methods:
addViewedId(id)
isViewed(id)

announcementModal#

Purpose:
Manages the single announcement modal state and interactions with the announcements list.
Key fields:
visible
id
remainingCount
Key methods:
open(id)
close()
flush()

announcements#

Purpose:
Controls visibility of the announcements list.
Key methods:
open()
close()

loginModal#

Purpose:
Central state for the login modal.
Key fields:
visible
checkoutPage
showShoppingListMessage
goToCheckoutPage
Key methods:
open(fromCheckout = false, fromShoppingList = false)
close(keepSuccessMessage = false)
Notes:
close() dispatches clear-login-modal-forms to clear forms.

productModal#

Purpose:
Holds the product modal (quick view) state.
Key fields:
visible
html
product
closeModalFlag
Key methods:
open(product, uniqueKey)
close()
Notes:
open(...) reads HTML from [x-ref=variantModalContent-<uniqueKey>].

checkout#

Purpose:
Holds checkout state and step validation.
Key fields:
data
isReady
steps (per-step enabled + valid)
currentStep
globalError
isUpdating
Key methods:
init()
set(data)
update(key, value)
setCurrent(step)
validateStep(step, isSelectable, stepsInvalid = false)
canShowDetails(step)

wishlist (conditional)#

Created only when window.showWishlist is enabled.
Purpose:
Holds wishlist item ids and provides a toggle(...) method.
Key methods:
init()
toggle(id, removeFromWishlistErrorMessage, addToWishlistErrorMessage)
readWishlistIds()
isInWishlist(id)
Notes:
Uses servicesreusabledefault.addItemToWishlist/removeItemFromWishlist.
Dispatches wishlistUpdated and writes localStorage.wishlistSync.

shoppingLists (conditional)#

Created only when window.showShoppingLists is enabled.
Purpose:
Manages the “save to shopping list” overlay/panel and list fetching.
Key fields:
visible, loading
list[]
dimension1Id, dimension2Id
Key methods:
init()
open(), close()
fetch()
isProductVariantInAnyList(variantId)
isInShoppingLists(product)
fetchSelectedVariantId(product)
Notes:
Fetches data through servicesreusabledefault.getShoppingLists().

darkMode#

Purpose:
Controls dark mode by toggling the dark class on <html>.
Storage:
Cookie darkMode.
Key fields/methods:
on (boolean)
init()
toggle()

Dependencies#

axios (global)
servicesreusabledefault (global)
Global flags/values from the rendered page:
userAuthenticated
window.showProductComparison

Notes#

theme.js must be defensive: it runs on every page.
Avoid editing vendor/minified scripts in Assets/js/*.min.js; wrap or re-init via theme.js where needed.
Modified at 2026-04-14 13:18:56
Previous
Overview
Next
Overview
Built with