PageSourceSearch

https://www.alpinestars.com/cdn/shop/t/196/assets/product-form.js?v=152639228011041886881789547723

js alpinestars.com collected 2026-10-02 05:45:58 UTC 22,740 bytes, 2 lines download raw bytes

1import{Component}from"@theme/component";import{fetchConfig,onAnimationEnd,yieldToMainThread,prefersReducedMotion}from"@theme/utilities";import{ThemeEvents,CartAddEvent,CartErrorEvent}from"@theme/events";import{cartPerformance}from"@theme/performance";import{morph}from"@theme/morph";const ERROR_MESSAGE_DISPLAY_DURATION=1e4,ERROR_BUTTON_REENABLE_DELAY=1e3,SUCCESS_MESSAGE_DISPLAY_DURATION=5e3;export function hasCompleteSizeSelection(root){const fieldsets=(root??document).querySelectorAll("fieldset.variant-option--grid");if(fieldsets.length===0)return!0;for(const fieldset of fieldsets)if(!fieldset.querySelector('input[type="radio"]:checked'))return!1;return!0}function sizeRequiredMessageScope(root){return root instanceof Element?root.closest("product-card, quick-add-component")??root.closest(".shopify-section")??root:root??document}export function hideSizeRequiredMessage(root){for(const message of sizeRequiredMessageScope(root).querySelectorAll("[data-size-required-message]"))message instanceof HTMLElement&&(message.classList.remove("is-visible"),message.setAttribute("aria-hidden","true"))}export function showSizeRequiredMessage(root){const scope=sizeRequiredMessageScope(root);hideSizeRequiredMessage(scope);const fieldsets=Array.from(scope.querySelectorAll("fieldset.variant-option--grid")).filter(fieldset=>fieldset instanceof HTMLElement);let firstUnselected=null,shownAny=!1;for(const fieldset of fieldsets){if(fieldset.querySelector('input[type="radio"]:checked'))continue;firstUnselected??=fieldset;const fieldsetMessage=fieldset.querySelector("[data-size-required-fieldset]");fieldsetMessage instanceof HTMLElement&&(fieldsetMessage.classList.add("is-visible"),fieldsetMessage.setAttribute("aria-hidden","false"),shownAny=!0)}if(!shownAny&&firstUnselected){const globalMessage=scope.querySelector(".product-form-buttons [data-size-required-message]")??scope.querySelector("[data-size-required-message]:not([data-size-required-fieldset])");globalMessage instanceof HTMLElement&&(globalMessage.classList.add("is-visible"),globalMessage.setAttribute("aria-hidden","false"))}return firstUnselected}export function scrollToSizeVariantPicker(root){const scope=root instanceof Element?root:document,picker=scope instanceof Element&&scope.matches("variant-picker")?scope:scope.querySelector("variant-picker");return picker instanceof HTMLElement?(picker.scrollIntoView({behavior:prefersReducedMotion()?"instant":"smooth",block:"start"}),picker.hasAttribute("tabindex")||picker.setAttribute("tabindex","-1"),picker.focus({preventScroll:!0}),!0):!1}export function getSizeSelectionScope(element,productId){const card=element.closest("product-card, quick-add-component");if(card)return card;const section=element.closest(".shopify-section");if(section){const picker=productId?section.querySelector(`variant-picker[data-product-id="${productId}"]`):section.querySelector("variant-picker");return picker instanceof HTMLElement?picker:section}return element.closest("dialog")}export class AddToCartComponent extends Component{requiredRefs=["addToCartButton"];#resetTimeouts=[];disconnectedCallback(){super.disconnectedCallback(),this.#resetTimeouts&&this.#resetTimeouts.forEach(timeoutId=>clearTimeout(timeoutId))}disable(){this.refs.addToCartButton.disabled=!0}enable(){this.refs.addToCartButton.disabled=!1}handleClick(event){const productForm=this.closest("product-form-component");if(productForm){const picker=getSizeSelectionScope(productForm,productForm.dataset.productId);if(!hasCompleteSizeSelection(picker)){event.preventDefault(),showSizeRequiredMessage(productForm),scrollToSizeVariantPicker(picker);return}}if(!this.closest("form")?.checkValidity())return;const quantitySelector=productForm?.refs.quantitySelector;quantitySelector?.canAddToCart&&!quantitySelector.canAddToCart().canAdd||(this.refs.addToCartButton.dataset.puppet!=="true"&&this.animateAddToCart(),this.refs.addToCartButton.type!=="submit"&&this.closest("form")?.requestSubmit())}animateAddToCart=async function(){const{addToCartButton}=this.refs;this.#resetTimeouts||(this.#resetTimeouts=[]),this.#resetTimeouts.forEac
1h(timeoutId2=>clearTimeout(timeoutId2)),this.#resetTimeouts=[],addToCartButton.dataset.added!=="true"&&(addToCartButton.dataset.added="true"),await yieldToMainThread(),await onAnimationEnd(addToCartButton);const timeoutId=setTimeout(()=>{addToCartButton.removeAttribute("data-added");const index=this.#resetTimeouts.indexOf(timeoutId);index>-1&&this.#resetTimeouts.splice(index,1)},800);this.#resetTimeouts.push(timeoutId)}}customElements.get("add-to-cart-component")||customElements.define("add-to-cart-component",AddToCartComponent);class ProductFormComponent extends Component{requiredRefs=["variantId","liveRegion"];#abortController=new AbortController;#timeout;#variantUpdateGeneration=0;connectedCallback(){super.connectedCallback();const{signal}=this.#abortController,target=this.closest(".shopify-section, dialog, product-card");target?.addEventListener(ThemeEvents.variantUpdate,this.#onVariantUpdate,{signal}),target?.addEventListener(ThemeEvents.variantSelected,this.#onVariantSelected,{signal}),document.addEventListener(ThemeEvents.cartUpdate,this.#onCartUpdate,{signal}),queueMicrotask(()=>this.#syncVariantIdForSizeSelection(null))}disconnectedCallback(){super.disconnectedCallback(),this.#abortController.abort()}#updateCartQuantityFromData(cart){const variantIdInput=this.querySelector('input[name="id"]');if(!variantIdInput?.value||!cart?.items)return 0;const cartItem=cart.items.find(item=>item.variant_id.toString()===variantIdInput.value.toString()),cartQty=cartItem?cartItem.quantity:0,quantitySelector=this.querySelector("quantity-selector-component");return quantitySelector?.setCartQuantity&&quantitySelector.setCartQuantity(cartQty),this.#updateQuantityLabel(cartQty),cartQty}async#fetchAndUpdateCartQuantity(){if(!this.querySelector('input[name="id"]')?.value)return 0;try{const cart=await(await fetch("/cart.js")).json();return this.#updateCartQuantityFromData(cart)}catch(error){return console.error("Failed to fetch cart quantity:",error),0}}#onCartUpdate=async event=>{if(event.detail?.sourceId===this.id||event.detail?.data?.source==="product-form-component")return;const cart=event.detail?.resource;cart?.items?this.#updateCartQuantityFromData(cart):await this.#fetchAndUpdateCartQuantity()};async handleSubmit(event){const{addToCartTextError}=this.refs;event.preventDefault(),this.#timeout&&clearTimeout(this.#timeout);const allAddToCartContainers=this.querySelectorAll("add-to-cart-component");if(Array.from(allAddToCartContainers).some(container=>container.refs.addToCartButton?.disabled))return;if(this.dataset.requiresSizeSelection==="true"){const picker=this.#getSectionVariantPicker();if(!hasCompleteSizeSelection(picker)){showSizeRequiredMessage(this),scrollToSizeVariantPicker(picker),this.#setLiveRegionText(this.querySelector("[data-size-required-message]")?.textContent?.trim()||picker?.querySelector("[data-size-required-message]")?.textContent?.trim()||"");return}if(hideSizeRequiredMessage(this),!this.refs.variantId.value&&!await this.#waitForResolvedVariantId()){showSizeRequiredMessage(this);return}}const form=this.querySelector("form");if(!form)throw new Error("Product form element missing");if(this.refs.quantitySelector?.canAddToCart){const validation=this.refs.quantitySelector.canAddToCart();if(!validation.canAdd){for(const container of allAddToCartContainers)container.disable();const errorMessage=(this.dataset.quantityErrorMax||"").replace("{{ maximum }}",validation.maxQuantity?.toString()||"");if(addToCartTextError){addToCartTextError.classList.remove("hidden");const textNode=addToCartTextError.childNodes[2];if(textNode)textNode.textContent=errorMessage;else{const newTextNode=document.createTextNode(errorMessage);addToCartTextError.appendChild(newTextNode)}this.#setLiveRegionText(errorMessage),this.#timeout&&clearTimeout(this.#timeout),this.#timeout=setTimeout(()=>{addToCartTextError&&(addToCartTextError.classList.add("hidden"),this.#clearLiveRegionText())},ERROR_MESSAGE_DISPLAY_DURATION)}setTimeout(()=>{for(const container of allAddToCartContainers)container.enable()},ERROR_BUTTON_REENABLE_DELAY);return}}const parentSection=this.closest(".shopify-section, dialog, product-card, section")||document;let productVariations=parentSection.querySelector('product-variations[data-selection-mode="checkbox"]');if(!productVariations){const allVariations=parentSection.querySelectorAll("product-variations");for(const variation of allVariations){const variationComponent=variation;if(variationComponent.hasSelectedVariations?.()){productVariations=variationComponent;break}}}if(productVariations?.hasSelectedVariations?.()){await this.#handleProductVariationsSubmit(event,productVariations,allAddToCartContainers
1);return}const formData=new FormData(form);if(typeof window.getSizebaySessionIdV4=="function"){const sizebaySessionId=window.getSizebaySessionIdV4();sizebaySessionId&&formData.append("attributes[SIZEBAY_SESSION_ID_V4]",sizebaySessionId)}const cartItemsComponents=document.querySelectorAll("cart-items-component"),cartItemComponentsSectionIds=[];cartItemsComponents.forEach(item=>{item instanceof HTMLElement&&item.dataset.sectionId&&cartItemComponentsSectionIds.push(item.dataset.sectionId),formData.append("sections",cartItemComponentsSectionIds.join(","))});const fetchCfg=fetchConfig("javascript",{body:formData});fetch(Theme.routes.cart_add_url,{...fetchCfg,headers:{...fetchCfg.headers,Accept:"text/html"}}).then(response=>response.json()).then(async response=>{if(response.status){if(this.dispatchEvent(new CartErrorEvent(form.getAttribute("id")||"",response.message,response.description,response.errors)),!addToCartTextError)return;addToCartTextError.classList.remove("hidden");const textNode=addToCartTextError.childNodes[2];if(textNode)textNode.textContent=response.message;else{const newTextNode=document.createTextNode(response.message);addToCartTextError.appendChild(newTextNode)}this.#setLiveRegionText(response.message),this.#timeout=setTimeout(()=>{addToCartTextError&&(addToCartTextError.classList.add("hidden"),this.#clearLiveRegionText())},ERROR_MESSAGE_DISPLAY_DURATION),this.dispatchEvent(new CartAddEvent({},this.id,{didError:!0,source:"product-form-component",itemCount:Number(formData.get("quantity"))||Number(this.dataset.quantityDefault),productId:this.dataset.productId}));return}else{const id=formData.get("id");if(addToCartTextError&&(addToCartTextError.classList.add("hidden"),addToCartTextError.removeAttribute("aria-live")),!id)throw new Error("Form ID is required");const anyAddToCartButton=allAddToCartContainers[0]?.refs.addToCartButton;if(anyAddToCartButton){const addedText=anyAddToCartButton.querySelector(".add-to-cart-text--added")?.textContent?.trim()||Theme.translations.added;this.#setLiveRegionText(addedText),setTimeout(()=>{this.#clearLiveRegionText()},SUCCESS_MESSAGE_DISPLAY_DURATION)}this.dispatchEvent(new CartAddEvent({},id.toString(),{source:"product-form-component",itemCount:Number(formData.get("quantity"))||Number(this.dataset.quantityDefault),productId:this.dataset.productId,sections:response.sections})),this.#fetchAndUpdateCartQuantity()}}).catch(error=>{console.error(error)}).finally(()=>{cartPerformance.measureFromEvent("add:user-action",event)})}async#handleProductVariationsSubmit(event,productVariations,allAddToCartContainers){const{addToCartTextError}=this.refs;for(const container of allAddToCartContainers)container.disable();try{const currentVariantId=this.querySelector('input[name="id"]')?.value||null,result=await productVariations.addSelectedToCart(currentVariantId);if(result.success){for(const container of allAddToCartContainers)container.animateAddToCart();const anyAddToCartButton=allAddToCartContainers[0]?.refs.addToCartButton;if(anyAddToCartButton){const addedText=anyAddToCartButton.querySelector(".add-to-cart-text--added")?.textContent?.trim()||Theme.translations.added;this.#setLiveRegionText(addedText),setTimeout(()=>{this.#clearLiveRegionText()},SUCCESS_MESSAGE_DISPLAY_DURATION)}await this.#fetchAndUpdateCartQuantity();const drawer=productVariations.closest("product-variations-drawer");if(drawer){const closeButton=drawer.querySelector('[ref="closeButton"]');closeButton instanceof HTMLElement&&closeButton.click()}}else if(addToCartTextError){addToCartTextError.classList.remove("hidden");const textNode=addToCartTextError.childNodes[2];if(textNode)textNode.textContent=result.error||"Error adding items to cart";else{const newTextNode=document.createTextNode(result.error||"Error adding items to cart");addToCartTextError.appendChild(newTextNode)}this.#setLiveRegionText(result.error||"Error adding items to cart"),this.#timeout=setTimeout(()=>{addToCartTextError&&(addToCartTextError.classList.add("hidden"),this.#clearLiveRegionText())},ERROR_MESSAGE_DISPLAY_DURATION)}}catch{if(addToCartTextError){addToCartTextError.classList.remove("hidden");const errorMsg="Error adding items to cart",textNode=addToCartTextError.childNodes[2];if(textNode)textNode.textContent=errorMsg;else{const newTextNode=document.createTextNode(errorMsg);addToCartTextError.appendChild(newTextNode)}this.#setLiveRegionText(errorMsg),this.#timeout=setTimeout(()=>{addToCartTextError&&(addToCartTextError.classList.add("hidden"),this.#clearLiveRegionText())},ERROR_MESSAGE_DISPLAY_DURATION)}}finally{setTimeout(()=>
1{for(const container of allAddToCartContainers)container.enable()},ERROR_BUTTON_REENABLE_DELAY),cartPerformance.measureFromEvent("add:user-action",event)}}#updateQuantityLabel(cartQty){const quantityLabel=this.refs.quantityLabelCartCount;if(quantityLabel){const inCartText=quantityLabel.textContent?.match(/\((\d+)\s+(.+)\)/);inCartText&&inCartText[2]&&(quantityLabel.textContent=`(${cartQty} ${inCartText[2]})`),quantityLabel.classList.toggle("hidden",cartQty===0)}}#setLiveRegionText(text){const liveRegion=this.refs.liveRegion;liveRegion.textContent=text}#clearLiveRegionText(){const liveRegion=this.refs.liveRegion;liveRegion.textContent=""}#getResponseProductFormRoot(html){const sectionId=this.dataset.sectionId,productId=this.dataset.productId,candidates=html.querySelectorAll("product-form-component");if(candidates.length===0)return null;if(candidates.length===1)return candidates[0]??null;for(const element of candidates)if(sectionId&&element.dataset.sectionId===sectionId&&productId&&element.dataset.productId===productId)return element;for(const element of candidates)if(sectionId&&element.dataset.sectionId===sectionId)return element;for(const element of candidates)if(productId&&element.dataset.productId===productId)return element;return candidates[0]??null}#morphOrUpdateElement(currentElement,newElement,insertReferenceElement=null){currentElement&&newElement?morph(currentElement,newElement):currentElement&&!newElement?currentElement.remove():!currentElement&&newElement&&insertReferenceElement&&insertReferenceElement.insertAdjacentElement("beforebegin",newElement.cloneNode(!0))}#getSectionVariantPicker(){const scope=getSizeSelectionScope(this,this.dataset.productId);return scope instanceof HTMLElement?scope:null}#waitForResolvedVariantId(timeoutMs=4e3){const{variantId}=this.refs;return variantId.value?Promise.resolve(!0):new Promise(resolve=>{const start=performance.now(),check=()=>{variantId.value?resolve(!0):performance.now()-start>=timeoutMs?resolve(!1):requestAnimationFrame(check)};requestAnimationFrame(check)})}async#syncVariantIdForSizeSelection(resource,generation=this.#variantUpdateGeneration){if(this.dataset.requiresSizeSelection!=="true"||generation!==this.#variantUpdateGeneration)return;const{variantId,acceleratedCheckoutButtonContainer}=this.refs,picker=this.#getSectionVariantPicker();if(!hasCompleteSizeSelection(picker)){variantId.value="",hideSizeRequiredMessage(picker),acceleratedCheckoutButtonContainer?.setAttribute("hidden","true");return}resource?.id!=null&&(variantId.value=String(resource.id));const checkedSize=picker?.querySelector('fieldset.variant-option--grid input[type="radio"]:checked'),sizeUnavailable=checkedSize instanceof HTMLInputElement&&(checkedSize.dataset.optionAvailable==="false"||checkedSize.getAttribute("aria-disabled")==="true"||checkedSize.closest("label")?.classList.contains("is-unavailable")===!0),resourceUnavailable=resource!=null&&resource.available===!1;if(sizeUnavailable||resourceUnavailable){if(variantId.value&&await this.#morphBuyButtonsForVariant(variantId.value,generation),generation!==this.#variantUpdateGeneration)return;acceleratedCheckoutButtonContainer?.setAttribute("hidden","true");return}if(!variantId.value||!this.querySelector("add-to-cart-component")&&(await this.#morphBuyButtonsForVariant(variantId.value,generation),generation!==this.#variantUpdateGeneration))return;hideSizeRequiredMessage(picker),acceleratedCheckoutButtonContainer?.removeAttribute("hidden");const{addToCartButtonContainer}=this.refs,button=addToCartButtonContainer?.refs.addToCartButton,addToCartText=this.dataset.addToCartText;if(addToCartButtonContainer&&button instanceof HTMLButtonElement){addToCartButtonContainer.enable();const textEl=button.querySelector(".add-to-cart-text__content");addToCartText&&textEl instanceof HTMLElement&&(textEl.textContent=addToCartText)}}async#morphBuyButtonsForVariant(variantId,generation=this.#variantUpdateGeneration){if(generation!==this.#variantUpdateGeneration)return;const productUrl=this.dataset.productUrl,sectionId=this.dataset.sectionId;if(!productUrl||!sectionId)return;const url=`${productUrl}?variant=${encodeURIComponent(String(variantId))}&section_id=${encodeURIComponent(sectionId)}`;try{const responseText=await(await fetch(url)).text();if(generation!==this.#variantUpdateGeneration)return;const html=new DOMParser().parseFromString(responseText,"text/html"),responseRoot=this.#getResponseProductFormRoot(html),currentAddToCartWrapper=this.querySelector('[ref="addToCartWrapper"]'),newAddToCartWrapper=responseRoot?.querySelector('[ref="addToCartWrapper"]');if(currentAddToCartWrapper&&newAddToCartWrapper&&morph(currentAddToCartWrapper,newAddToCartWrapper),generation===this.#variantUpdateGeneration){const{variantId:variantIdInput}=this.refs;variantIdInput.value=String(variantId)}}catch(error){console.error(error)}}#onVariantUpdate=async event=>{const generation=++this.#variantUpdateGeneration;if(event.detail.data.newProduct)this.dataset.productId=event.detail.data.newProduct.id;else if(event.detail.data.productId!==this.dataset.productId)return;const{variantId}=this.refs,responseRoot=this.#getResponseProductFormRoot(event.detail.data.html);variantId.value=event.detail.resource?.id??"";const{addToCartButtonContainer:currentAddToCartButtonContainer,acceleratedCheckoutButtonContainer}=this.refs,currentAddToCartButton=currentAddToCartButtonContainer?.refs.addToCartButton,currentAddToCartWrapper=this.querySelector('[ref="addToCartWrapper"]'),newAddToCartWrapper=responseRoot?.querySelector('[ref="addToCartWrapper"]');if(currentAddToCartWrapper&&newAddToCartWrapper)morph(currentAddToCartWrapper,newAddToCartWrapper),variantId.value=event.detail.resource?.id??"";else if(currentAddToCartButtonContainer&&currentAddToCartButton){event.detail.resource==null||event.detail.resource.available==!1?currentAddToCartButtonContainer.disable():currentAddToCartButtonContainer.enable();const newAddToCartButton=responseRoot?.querySelector('[ref="addToCartButton"]');newAddToCartButton&&morph(currentAddToCartButton,newAddToCartButton)}if(generation!==this.#variantUpdateGeneration)return;this.dataset.requiresSizeSelection!=="true"&&acceleratedCheckoutButtonContainer&&(event.detail.resource==null||event.detail.resource.available==!1?acceleratedCheckoutButtonContainer.setAttribute("hidden","true"):acceleratedCheckoutButtonContainer.removeAttribute("hidden"));const{quantityRules,pricePerItem,quantitySelector,productFormButtons,quantityLabel,quantitySelectorWrapper}=this.refs,newQuantityInput=responseRoot?.querySelector('quantity-selector-component input[ref="quantityInput"]');quantitySelector?.updateConstraints&&newQuantityInput&&quantitySelector.updateConstraints(newQuantityInput.min,newQuantityInput.max||null,newQuantityInput.step);const newQuantityRules=responseRoot?.querySelector(".quantity-rules"),isQuantityRulesChanging=!!quantityRules!=!!newQuantityRules,newPricePerItem=responseRoot?.querySelector("price-per-item");if((isQuantityRulesChanging||!!pricePerItem!=!!newPricePerItem)&&quantitySelector){const currentQuantityValue=quantitySelector.getValue?.(),newProductFormButtons=responseRoot?.querySelector(".product-form-buttons");if(productFormButtons&&newProductFormButtons){morph(productFormButtons,newProductFormButtons);const newQuantityInputElement=responseRoot?.querySelector('quantity-selector-component input[ref="quantityInput"]');this.refs.quantitySelector?.updateConstraints&&newQuantityInputElement&&currentQuantityValue&&(this.refs.quantitySelector.setValue(currentQuantityValue),this.refs.quantitySelector.updateConstraints(newQuantityInputElement.min,newQuantityInputElement.max||null,newQuantityInputElement.step)),variantId.value=event.detail.resource?.id??""}}else{const morphTargets=[[".quantity-label",quantityLabel,quantitySelector],[".quantity-rules",quantityRules,this.refs.productFormButtons],["price-per-item",pricePerItem,quantitySelectorWrapper]];for(const[selector,currentElement,fallback]of morphTargets)this.#morphOrUpdateElement(currentElement,responseRoot?.querySelector(selector),fallback)}if(generation!==this.#variantUpdateGeneration)return;const currentVolumePricing=this.refs.volumePricing,newVolumePricing=responseRoot?.querySelector("volume-pricing");this.#morphOrUpdateElement(currentVolumePricing,newVolumePricing,this.refs.productFormButtons),await this.#syncVariantIdForSizeSelection(event.detail.resource,generation),!(generation!==this.#variantUpdateGeneration||!(quantityRules||newQuantityRules||pricePerItem||newPricePerItem||currentVolumePricing||newVolumePricing))&&await this.#fetchAndUpdateCartQuantity()};#onVariantSelected=()=>
1{if(this.dataset.requiresSizeSelection!=="true")return;const picker=this.#getSectionVariantPicker();if(!hasCompleteSizeSelection(picker)){this.refs.variantId.value="";return}if((picker?.querySelectorAll("fieldset.variant-option--grid").length??0)>1){this.refs.variantId.value="";return}const checkedSize=picker?.querySelector('fieldset.variant-option--grid input[type="radio"]:checked');checkedSize instanceof HTMLInputElement&&checkedSize.dataset.variantId&&(this.refs.variantId.value=checkedSize.dataset.variantId)}}customElements.get("product-form-component")||customElements.define("product-form-component",ProductFormComponent);
2//# sourceMappingURL=/cdn/shop/t/196/assets/product-form.js.map?v=152639228011041886881789547723

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.