1/*! Copyright (c) Safe As Milk. All rights reserved. */class VariantSelects extends HTMLElement{#addToCartText;#boundCacheAdjacentVariants;#variantDataCache;#lastFetchRetryKey=null;#fetchRetryCount=0;#FETCH_RETRY_COUNT=3;#FETCH_RETRY_DELAY=1e3;constructor(){super(),this.#boundCacheAdjacentVariants=this.#cacheAdjacentVariants.bind(this)}connectedCallback(){this.updateOptions(),this.updateGalleryOnVariantChange=this.hasAttribute("data-update-gallery-on-variant-change"),this.#variantDataCache=new Map;const currentSection=this.closest(".js-section__product-single");currentSection&&this.#variantDataCache.set(this.optionValueIds.join(","),this.#prepareTemplate(currentSection.outerHTML)),this.intersectionObserver=new IntersectionObserver((entries=>{entries.forEach((entry=>{entry.isIntersecting&&(this.#boundCacheAdjacentVariants(),this.intersectionObserver.disconnect())}))})),this.intersectionObserver.observe(this),this.uniqueId=this.dataset.card||this.dataset.section,this.#addToCartText=this.dataset.addToCartText||window.theme.localize("ADD_TO_CART"),this.#updateVariantOptionStates(),this.addEventListener("change",this.onVariantChange)}disconnectedCallback(){this.removeEventListener("change",this.onVariantChange),this.#variantDataCache.clear(),this.intersectionObserver&&this.intersectionObserver.disconnect()}async onVariantChange({target},isRefetch=!1){isRefetch||(this.previouslyCorrectOptionValueIds=[...this.optionValueIds]),this.updateOptions(),this.removeErrorMessage();const currentlyFocusedElementId=document.activeElement?.id,optionValuesString=this.optionValueIds.join(","),viewParams=this.dataset.viewId?`?view=${this.dataset.viewId}`:"",sectionParams=this.dataset.section?`${viewParams?"&":"?"}section_id=${this.dataset.section}`:"",params=optionValuesString?`${sectionParams||viewParams?"&":"?"}option_values=${optionValuesString}`:"",cachedVariantData=this.#variantDataCache.get(optionValuesString);let template;if(cachedVariantData)template=cachedVariantData instanceof Promise?await cachedVariantData:cachedVariantData;else{const[combinedListingOptionId]=Object.keys(this.combinedListingsUrls).filter((id=>this.optionValueIds.includes(id))),url=combinedListingOptionId?this.combinedListingsUrls[combinedListingOptionId]:this.dataset.url,response=await fetch(`${url}${viewParams}${sectionParams}${params}`);if(response.ok)isRefetch&&(this.previouslyCorrectOptionValueIds=[...this.optionValueIds]);else{if(this.#lastFetchRetryKey!==optionValuesString&&(this.#lastFetchRetryKey=optionValuesString,this.#fetchRetryCount=0),this.#lastFetchRetryKey===optionValuesString&&this.#fetchRetryCount<this.#FETCH_RETRY_COUNT){this.#fetchRetryCount+=1,this.#lastFetchRetryKey=optionValuesString,setTimeout((async()=>{console.warn(`(${this.#fetchRetryCount}/${this.#FETCH_RETRY_COUNT}) Trying to re-fetch variant for options combination: `,optionValuesString),this.onVariantChange({target},!0)}),this.#FETCH_RETRY_DELAY);return}this.#fetchRetryCount=0,this.#lastFetchRetryKey=null,this.#renderError(`Failed to fetch variant for options combination: ${optionValuesString}`),this.resetOptionsToPreviouslyCorrect();return}const data=await response.text();if(template=this.#prepareTemplate(data),this.#variantDataCache.size>=100){const oldestKey=this.#variantDataCache.keys().next().value;this.#variantDataCache.delete(oldestKey)}this.#variantDataCache.set(optionValuesString,template)}const html=template.content.cloneNode(!0),productElement=this.closest("product-single, quick-shop"),productElementTag=productElement?.tagName.toLowerCase(),oldProductUrl=productElement?.dataset.productUrl,newProductUrl=target.tagName==="SELECT"?target.options[target.selectedIndex].dataset.productUrl:target.dataset.productUrl;if(newProductUrl&&oldProductUrl!==newProductUrl){const newContent=html.querySelector(productElement.tagName.toLowerCase());Array.from(this.querySelectorAll("[data-a11y-dialog-show]")).forEach((el=>{const popup=document.getElementById(el.dataset.a11yDialogShow);popup&&popup.remove()})),productElementTag==="quick-shop"?(productElement.updateContent(newContent),productElement.dataset.productUrl=newProductUrl):(productElement.parentNode.insertBefore(newContent,productElement),productElement.remove());const newVariantSelects=document.querySelector("variant-selects, variant-radios, variant-mixed-inputs");if(newVariantSelects){newVariantSelects.querySelectorAll('input[type="radio"][checked]').forEach((radioInput=>{const el=radioInput;el.checked=!0})),newVariantSelects.updateOptions();const checkedInput=newVariantSelects.querySelector('input[type="radio"]:checked');checkedInput&&checkedInput.dispatchEvent(new Event("change",{bubbles:!0}))}currentlyFocusedElementId&&document.getElementById(currentlyFocusedElementId)?.focus(),this.dataset.updateUrl!=="false"&&window.history.pushState({},"",newProductUrl);return}if(!JSON.parse(html.querySelector(`#variant-data-${this.uniqueId}`).textContent)?.id)this.toggleAddButton(!0,""),this.setUnavailable(),this.#updateVariantOptionStates();else{const newVariantSelectors=html.querySelector(`#variant-selectors-${this.uniqueId}`);if(newVariantSelectors){const oldVariantDataElement=this.querySelector(`#variant-data-${this.uniqueId}`),newVariantDataElement=html.querySelector(`#variant-data-${this.uniqueId}`);oldVariantDataElement&&newVariantDataElement&&(oldVariantDataElement.textContent=newVariantDataElement.textContent),Array.from(this.querySelectorAll("[data-a11y-dialog-show]")).forEac
1h((el=>{const popup=document.getElementById(el.dataset.a11yDialogShow);popup&&popup.remove()})),this.innerHTML=newVariantSelectors.innerHTML}this.updateMasterId(),this.currentVariant.available?this.toggleAddButton(!1):this.toggleAddButton(!0,window.theme.localize("SOLD_OUT"));const oldPriceContainer=document.getElementById(`price-${this.uniqueId}`),newPriceContainer=html.getElementById(`price-${this.uniqueId}`);oldPriceContainer&&newPriceContainer&&(oldPriceContainer.innerHTML=newPriceContainer.innerHTML,oldPriceContainer.removeAttribute("hidden"));const oldUnitPriceContainer=document.getElementById(`unit-price-${this.uniqueId}`),newUnitPriceContainer=html.getElementById(`unit-price-${this.uniqueId}`);oldUnitPriceContainer&&newUnitPriceContainer&&(oldUnitPriceContainer.innerHTML=newUnitPriceContainer.innerHTML);const oldLabelContainer=document.getElementById(`label-${this.uniqueId}`),newLabelContainer=html.getElementById(`label-${this.uniqueId}`);oldLabelContainer&&newLabelContainer&&(oldLabelContainer.innerHTML=newLabelContainer.innerHTML);const oldLabelsContainer=document.getElementById(`labels-${this.uniqueId}`),newLabelsContainer=html.getElementById(`labels-${this.uniqueId}`);oldLabelsContainer&&newLabelsContainer&&(oldLabelsContainer.innerHTML=newLabelsContainer.innerHTML);const oldInventoryNoticeContainer=document.getElementById(`inventory-notice-${this.uniqueId}`),newInventoryNoticeContainer=html.getElementById(`inventory-notice-${this.uniqueId}`);oldInventoryNoticeContainer&&newInventoryNoticeContainer&&(oldInventoryNoticeContainer.innerHTML=newInventoryNoticeContainer.innerHTML);const skuContainer=document.getElementById(`sku-${this.uniqueId}`),newSkuContainer=html.getElementById(`sku-${this.uniqueId}`);skuContainer&&newSkuContainer&&(skuContainer.innerHTML=newSkuContainer.innerHTML);const barcodeContainer=document.getElementById(`barcode-${this.uniqueId}`),newBarcodeContainer=html.getElementById(`barcode-${this.uniqueId}`);barcodeContainer&&newBarcodeContainer&&(barcodeContainer.innerHTML=newBarcodeContainer.innerHTML);const oldPaymentTerms=document.getElementById(`product-form-${this.uniqueId}`)?.querySelector(".shopify-payment-terms"),newPaymentTerms=html.querySelector(`#product-form-${this.uniqueId}`)?.querySelector(".shopify-payment-terms");if(oldPaymentTerms&&newPaymentTerms&&(oldPaymentTerms.innerHTML=newPaymentTerms.innerHTML),this.updateGalleryOnVariantChange&&productElement.tagName==="PRODUCT-SINGLE"){const newMediaGallery=html.getElementById(`media-gallery-${this.uniqueId}`);productElement.updateGallery(newMediaGallery)}this.updateURL(),this.updateVariantInput(),this.updatePickupAvailability(),currentlyFocusedElementId&&document.getElementById(currentlyFocusedElementId)?.focus(),this.#cacheAdjacentVariants(),this.#updateVariantOptionStates();const mediaGallery=productElement.querySelector("media-gallery");this.dispatchEvent(new CustomEvent("on:variant:change",{detail:{mediaGallery,variant:this.currentVariant}})),document.dispatchEvent(new CustomEvent("variant:changed",{bubbles:!0,detail:{variant:this.currentVariant,sectionId:this.uniqueId}}))}}setOptionByValueId(valueId){if(!valueId)return;const optionElement=this.querySelector(`[data-option-value-id="${valueId}"]`);if(optionElement?.tagName==="INPUT")optionElement.click();else if(optionElement?.tagName==="OPTION"){const selectElement=optionElement.closest("select");selectElement.value=optionElement.value,selectElement.dispatchEvent(new Event("change",{bubbles:!0}))}}updateOptions(){this.options=Array.from(this.querySelectorAll("select"),(select=>select.value)),this.optionValueIds=Array.from(this.querySelectorAll("select"),(select=>select.options[select.selectedIndex].dataset.optionValueId)),this.adjacentOptionValueIds=Array.from(this.querySelectorAll("select")).reduce(((acc,select,index)=>{const unselectedOptions=Array.from(select.options).filter((option=>option.dataset.optionValueId!==select.options[select.selectedIndex].dataset.optionValueId));return[...acc,...unselectedOptions.map((option=>[...this.optionValueIds.slice(null,index),option.dataset.optionValueId,...this.optionValueIds.slice(index+1)]))]}),[]),this.combinedListingsUrls=Array.from(this.querySelectorAll("select option[data-product-url]")).reduce(((acc,option)=>({...acc,[option.dataset.optionValueId]:option.dataset.productUrl})),{})}resetOptionsToPreviouslyCorrect(){this.previouslyCorrectOptionValueIds.forEach((option=>{const optionElement=this.querySelector(`option[data-option-value-id="${option}"]`);optionElement&&(optionElement.closest("select").value=optionElement.value)}))}updateMasterId(){this.currentVariant=JSON.parse(this.querySelector('[type="application/json"]').textContent)}updateURL(){!this.currentVariant?.id||this.dataset.updateUrl==="false"||window.history.replaceState({},"",`${this.dataset.url}?variant=${this.currentVariant.id}`)}updateVariantInput(){document.querySelectorAll(`#product-form-${this.uniqueId}, #product-form-installment-${this.uniqueId}`).forEach((productForm=>{const input=productForm.querySelector('input[name="id"]');input.value=this.currentVariant.id,input.dispatchEvent(new Event("change",{bubbles:!0}))}
1));const productSingle=this.closest("product-single");productSingle&&(productSingle.variant=this.currentVariant)}updatePickupAvailability(){const pickupAvailability=document.querySelector(`#products-availability-${this.uniqueId} pickup-availability`);pickupAvailability&&(pickupAvailability.removeAttribute("hidden"),pickupAvailability.fetchAvailability(this.currentVariant.id))}removeErrorMessage(){const error=this.querySelector(".errors");error&&error.remove();const section=this.closest("section");section&§ion.querySelector(".qty-error")?.remove()}toggleAddButton(disable=!0,text=""){const productForm=document.getElementById(`product-form-${this.uniqueId}`);if(!productForm)return;const buttonsContainer=productForm.querySelector(".js-product-buttons"),addButton=productForm.querySelector('[name="add"]'),addButtonText=productForm.querySelector('[name="add"] staged-action-text');addButton&&(disable?(addButton.setAttribute("disabled","disabled"),text&&(addButtonText.textContent=text),buttonsContainer.classList.add("is-disabled")):(addButton.removeAttribute("disabled"),addButtonText.textContent=this.#addToCartText,buttonsContainer.classList.remove("is-disabled")))}setUnavailable(){const productForm=document.getElementById(`product-form-${this.uniqueId}`),addButton=productForm.querySelector('[name="add"]'),addButtonText=productForm.querySelector('[name="add"] staged-action-text'),inventoryNoticeContainer=document.getElementById(`inventory-notice-${this.uniqueId}`),soldClass="stock-note--sold",inStockClass="stock-note--in-stock",lowStockClass="stock-note--low";if(inventoryNoticeContainer){const inventoryNoticeWrapperContainer=inventoryNoticeContainer.querySelector(".stock-note"),inventoryNoticeTextContainer=inventoryNoticeContainer.querySelector(".stock-note__text");inventoryNoticeWrapperContainer.classList.remove(inStockClass,lowStockClass),inventoryNoticeWrapperContainer.classList.add(soldClass),inventoryNoticeTextContainer.innerHTML=window.theme.localize("QTY_NOTICE_SOLD_OUT")}const pickupAvailability=document.querySelector(`#products-availability-${this.uniqueId} pickup-availability`);pickupAvailability&&pickupAvailability.setAttribute("hidden","");const price=document.getElementById(`price-${this.uniqueId}`),buttonsContainer=productForm.querySelector(".js-product-buttons");addButton&&(addButton.setAttribute("disabled","disabled"),addButtonText.textContent=window.theme.localize("UNAVAILABLE"),buttonsContainer.classList.add("is-disabled"),price&&price.setAttribute("hidden",""))}get#allVariants(){const json=this.querySelector(`#all-variant-data-${this.uniqueId}`);if(!json)return[];try{const data=JSON.parse(json.textContent);return Array.isArray(data)?data:[]}catch{return[]}}#updateVariantOptionStates(){this.#cleanFirstSelectGroup();const variants=this.#allVariants;if(!variants.length||variants.length>=250)return;const selectedOptions=this.options;selectedOptions?.length&&(this.#updateButtonStates(variants,selectedOptions),this.#updateSelectLabels(variants,selectedOptions))}#cleanFirstSelectGroup(){const optionGroups=Array.from(this.querySelectorAll("fieldset, select"));if(optionGroups.length<=1)return;const firstGroup=optionGroups[0];firstGroup.tagName==="SELECT"&&Array.from(firstGroup.options).forEach((optionElement=>{const el=optionElement;el.dataset.baseText&&(el.textContent=el.dataset.baseText)}))}#updateButtonStates(variants,selectedOptions){const optionGroups=Array.from(this.querySelectorAll("fieldset, select")),totalGroups=optionGroups.length;optionGroups.forEach(((group,optionIndex)=>{group.tagName==="FIELDSET"&&Array.from(group.querySelectorAll("input")).forEach((input=>{const label=input.nextElementSibling;if(!label)return;if(optionIndex===0&&totalGroups>1){label.classList.remove("is-disabled");return}const candidateOptions=[...selectedOptions];candidateOptions[optionIndex]=input.value;const hasAvailableMatch=variants.some((variant=>variant.available&&variant.options.every(((optionValue,index)=>optionValue===candidateOptions[index]))));label.classList.toggle("is-disabled",!hasAvailableMatch)}))}))}#updateSelectLabels(variants,selectedOptions){const soldOutText=window.theme.localize("SOLD_OUT"),unavailableText=window.theme.localize("UNAVAILABLE"),optionGroups=Array.from(this.querySelectorAll("fieldset, select")),totalGroups=optionGroups.length;
1optionGroups.forEach(((group,optionIndex)=>{group.tagName==="SELECT"&&(optionIndex===0&&totalGroups>1||Array.from(group.options).forEach((optionElement=>{const el=optionElement;let baseText;el.dataset.baseText?baseText=el.dataset.baseText:(baseText=el.textContent.trim(),baseText=baseText.replace(new RegExp(`\\s+-\\s+${soldOutText}`,"g"),""),baseText=baseText.replace(new RegExp(`\\s+-\\s+${unavailableText}`,"g"),""),baseText=baseText.trim());const candidateOptions=[...selectedOptions];candidateOptions[optionIndex]=el.value;const matchingVariants=variants.filter((variant=>variant.options.every(((optionValue,index)=>optionValue===candidateOptions[index]))));matchingVariants.length?matchingVariants.some((variant=>variant.available))?el.textContent=baseText:el.textContent=`${baseText} - ${soldOutText}`:el.textContent=`${baseText} - ${unavailableText}`})))}))}#cacheAdjacentVariants(){this.#variantDataCache&&this.adjacentOptionValueIds.forEach((ids=>{const key=ids.join(",");if(this.#variantDataCache.has(key))return;if(this.#variantDataCache.size>=100){const oldestKey=this.#variantDataCache.keys().next().value;this.#variantDataCache.delete(oldestKey)}const viewParams=this.dataset.viewId?`?view=${this.dataset.viewId}`:"",sectionParams=this.dataset.section?`${viewParams?"&":"?"}section_id=${this.dataset.section}`:"",params=key?`${sectionParams||viewParams?"&":"?"}option_values=${key}`:"",[combinedListingOptionId]=Object.keys(this.combinedListingsUrls).filter((id=>ids.includes(id))),url=combinedListingOptionId?this.combinedListingsUrls[combinedListingOptionId]:this.dataset.url,promise=fetch(`${url}${viewParams}${sectionParams}${params}`).then((response=>response.text().then((text=>{if(!response.ok)return this.#variantDataCache.delete(key),console.warn("Failed to cache variant data for: ",key),"";const template=this.#prepareTemplate(text);return this.#variantDataCache.set(key,template),template}))));this.#variantDataCache.set(key,promise)}))}#prepareTemplate(data){const template=document.createElement("template");template.innerHTML=data;const{firstElementChild}=template.content;if(firstElementChild.tagName==="QUICK-SHOP"){const quickShopId=firstElementChild.id,elementIdsToChange=firstElementChild.querySelectorAll(`[id$="${quickShopId}"]`),elementFormIdToChange=firstElementChild.querySelectorAll(`[form$="${quickShopId}"]`),elementForIdToChange=firstElementChild.querySelectorAll(`[for$="${quickShopId}"]`);elementIdsToChange.forEach((el=>{el.setAttribute("id",`${el.getAttribute("id").replace(quickShopId,this.uniqueId)}`),el.getAttribute("id").includes("variant-selectors")&&el.setAttribute("data-card",this.uniqueId)})),elementFormIdToChange.forEach((el=>el.setAttribute("form",`${el.getAttribute("form").replace(quickShopId,this.uniqueId)}`))),elementForIdToChange.forEach((el=>el.setAttribute("for",`${el.getAttribute("for").replace(quickShopId,this.uniqueId)}`))),firstElementChild.setAttribute("aria-labelledby",firstElementChild.getAttribute("aria-labelledby").replace(quickShopId,this.uniqueId))}return template}#renderError(message){this.removeErrorMessage();const error=document.createElement("div");error.classList.add("errors","qty-error","u-small"),error.innerHTML=message,this.prepend(error)}}customElements.define("variant-selects",VariantSelects);class VariantRadios extends VariantSelects{updateOptions(){const fieldsets=Array.from(this.querySelectorAll("fieldset"));this.options=fieldsets.map((fieldset=>Array.from(fieldset.querySelectorAll("input")).find((radio=>radio.checked))?.value)),this.optionValueIds=fieldsets.map((fieldset=>Array.from(fieldset.querySelectorAll("input")).find((radio=>radio.checked))?.dataset.optionValueId)),this.adjacentOptionValueIds=fieldsets.reduce(((acc,fieldset,index)=>{const uncheckedInputs=Array.from(fieldset.querySelectorAll("input:not([checked])"));return[...acc,...uncheckedInputs.map((input=>[...this.optionValueIds.slice(null,index),input.dataset.optionValueId,...this.optionValueIds.slice(index+1)]))]}),[]),this.combinedListingsUrls=Array.from(this.querySelectorAll("fieldset input[data-product-url]")).reduce(((acc,input)=>({...acc,[input.dataset.optionValueId]:input.dataset.productUrl})),{})}resetOptionsToPreviouslyCorrect(){this.previouslyCorrectOptionValueIds.forEach((option=>{const input=this.querySelector(`input[data-option-value-id="${option}"]`);input&&(input.checked=!0)}))}}customElements.define("variant-radios",VariantRadios);class VariantSwatches extends HTMLElement{connectedCallback(){const checkedInput=this.querySelector("input[checked]");checkedInput.checked=!0,this.currentSelection=checkedInput?.value;const form=document.getElementById(this.dataset.formId);form?form.addEventListener("change",(()=>{this.updateLabel()})):this.addEventListener("change",(()=>{this.updateLabel()})),this.bindHoverEvents()}updateLabel(){const currentSelection=this.querySelector("input[checked]").value;if(currentSelection!==this.currentSelection){const labelOptionElement=this.querySelector(".js-option-title");labelOptionElement.innerHTML=currentSelection,this.currentSelection=currentSelection}}bindHoverEvents(){const swatches=this.querySelectorAll(".product-form__swatch__item"),labelOptionElement=this.querySelector(".js-option-title");let resetTimeout;
1swatches.forEach((swatch=>{const label=swatch.querySelector("label"),input=swatch.querySelector("input");label.addEventListener("mouseenter",(()=>{clearTimeout(resetTimeout),input&&(labelOptionElement.textContent=input.value)})),label.addEventListener("mouseleave",(()=>{resetTimeout=setTimeout((()=>{labelOptionElement.textContent=this.currentSelection}),200)}))}))}}customElements.define("variant-swatches",VariantSwatches);class VariantMixedInputs extends VariantSelects{updateOptions(){this.options=Array.from(this.querySelectorAll("input:checked, select"),(element=>element.value)),this.optionValueIds=Array.from(this.querySelectorAll("input:checked, select"),(element=>element.tagName==="INPUT"?element.dataset.optionValueId:element.options[element.selectedIndex].dataset.optionValueId)),this.adjacentOptionValueIds=Array.from(this.querySelectorAll("fieldset, select")).reduce(((acc,element,index)=>{const unselectedOptions=element.tagName==="SELECT"?Array.from(element.options).filter((option=>option.dataset.optionValueId!==element.options[element.selectedIndex].dataset.optionValueId)):Array.from(element.querySelectorAll("input:not(:checked)"));return[...acc,...unselectedOptions.map((option=>[...this.optionValueIds.slice(null,index),option.dataset.optionValueId,...this.optionValueIds.slice(index+1)]))]}),[]),this.combinedListingsUrls=Array.from(this.querySelectorAll("fieldset input[data-product-url], select option[data-product-url]")).reduce(((acc,element)=>({...acc,[element.dataset.optionValueId]:element.dataset.productUrl})),{})}resetOptionsToPreviouslyCorrect(){this.previouslyCorrectOptionValueIds.forEach((option=>{const element=this.querySelector(`input[data-option-value-id="${option}"], option[data-option-value-id="${option}"]`);element&&element.tagName==="INPUT"?element.checked=!0:element&&element.tagName==="OPTION"&&(element.closest("select").value=element.value)}))}}customElements.define("variant-mixed-inputs",VariantMixedInputs); 2//# sourceMappingURL=/cdn/shop/t/6/assets/variant-select-components.js.map?v=90822423601313536321782245198
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.