import{Component}from"@theme/component";import{VariantSelectedEvent,VariantUpdateEvent}from"@theme/events";import{morph}from"@theme/morph";import{requestYieldCallback}from"@theme/utilities";export default class VariantPicker extends Component{#pendingRequestUrl;#abortController;connectedCallback(){super.connectedCallback(),this.addEventListener("change",this.variantChanged.bind(this))}variantChanged(event){if(!(event.target instanceof HTMLElement))return;const selectedOption=event.target instanceof HTMLSelectElement?event.target.options[event.target.selectedIndex]:event.target;if(!selectedOption)return;this.updateSelectedOption(event.target),this.dispatchEvent(new VariantSelectedEvent({id:selectedOption.dataset.optionValueId??""}));const isOnProductPage=this.dataset.templateProductMatch==="true"&&!event.target.closest("product-card")&&!event.target.closest("quick-add-dialog"),currentUrl=this.dataset.productUrl?.split("?")[0],newUrl=selectedOption.dataset.connectedProductUrl,loadsNewProduct=isOnProductPage&&!!newUrl&&newUrl!==currentUrl;this.fetchUpdatedSection(this.buildRequestUrl(selectedOption),loadsNewProduct);const url=new URL(window.location.href),variantId=selectedOption.dataset.variantId||null;isOnProductPage&&(variantId?url.searchParams.set("variant",variantId):url.searchParams.delete("variant")),loadsNewProduct&&(url.pathname=newUrl),url.href!==window.location.href&&requestYieldCallback(()=>{history.replaceState({},"",url.toString())})}updateSelectedOption(target){if(typeof target=="string"){const targetElement=this.querySelector(`[data-option-value-id="${target}"]`);if(!targetElement)throw new Error("Target element not found");target=targetElement}if(target instanceof HTMLInputElement&&(target.checked=!0),target instanceof HTMLSelectElement){const newValue=target.value,newSelectedOption=Array.from(target.options).find(option=>option.value===newValue);if(!newSelectedOption)throw new Error("Option not found");for(const option of target.options)option.removeAttribute("selected");newSelectedOption.setAttribute("selected","selected")}}buildRequestUrl(selectedOption,source=null,sourceSelectedOptionsValues=[]){let productUrl=selectedOption.dataset.connectedProductUrl||this.#pendingRequestUrl||this.dataset.productUrl;this.#pendingRequestUrl=productUrl;const params=[];return this.selectedOptionsValues.length&&!source?params.push(`option_values=${this.selectedOptionsValues.join(",")}`):source==="product-card"&&(this.selectedOptionsValues.length?params.push(`option_values=${sourceSelectedOptionsValues.join(",")}`):params.push(`option_values=${selectedOption.dataset.optionValueId}`)),this.closest("quick-add-component")||this.closest("swatches-variant-picker-component")?(productUrl?.includes("?")&&(productUrl=productUrl.split("?")[0]),`${productUrl}?section_id=section-rendering-product-card&${params.join("&")}`):`${productUrl}?${params.join("&")}`}fetchUpdatedSection(requestUrl,shouldMorphMain=!1){this.#abortController?.abort(),this.#abortController=new AbortController,fetch(requestUrl,{signal:this.#abortController.signal}).then(response=>response.text()).then(responseText=>{this.#pendingRequestUrl=void 0;const html=new DOMParser().parseFromString(responseText,"text/html");html.querySelector("overflow-list[defer]")?.removeAttribute("defer");const textContent=html.querySelector('variant-picker script[type="application/json"]')?.textContent;if(textContent)if(shouldMorphMain)this.updateMain(html);else{const newProduct=this.updateVariantPicker(html);this.selectedOptionId&&this.dispatchEvent(new VariantUpdateEvent(JSON.parse(textContent),this.selectedOptionId,{html,productId:this.dataset.productId??"",newProduct}))}}).catch(error=>{error.name==="AbortError"?console.warn("Fetch aborted by user"):console.error(error)})}updateVariantPicker(newHtml){let newProduct;const newVariantPickerSource=newHtml.querySelector(this.tagName.toLowerCase());if(!newVariantPickerSource)throw new Error("No new variant picker source found");if(newVariantPickerSource instanceof HTMLElement){const newProductId=newVariantPickerSource.dataset.productId,newProductUrl=newVariantPickerSource.dataset.productUrl;newProductId&&newProductUrl&&this.dataset.productId!==newProductId&&(newProduct={id:newProductId,url:newProductUrl}),this.dataset.productId=newProductId,this.dataset.productUrl=newProductUrl}return morph(this,newVariantPickerSource),newProduct}updateMain(newHtml){const main=document.querySelector("main"),newMain=newHtml.querySelector("main");if(!main||!newMain)throw new Error("No new main source found");morph(main,newMain)}get selectedOption(){const selectedOption=this.querySelector("select option[selected], fieldset input:checked");if(selectedOption instanceof HTMLInputElement||selectedOption instanceof HTMLOptionElement)return selectedOption}get selectedOptionId(){const{selectedOption}=this;if(!selectedOption)return;const{optionValueId}=selectedOption.dataset;if(!optionValueId)throw new Error("No option value ID found");return optionValueId}get selectedOptionsValues(){return Array.from(this.querySelectorAll("select option[selected], fieldset input:checked")).map(option=>{const{optionValueId}=option.dataset;if(!optionValueId)throw new Error("No option value ID found");return optionValueId})}}customElements.get("variant-picker")||customElements.define("variant-picker",VariantPicker); //# sourceMappingURL=/cdn/shop/t/47/assets/variant-picker.js.map?v=113536721324242252251757451905