PageSourceSearch

https://lorenacanals.com/cdn/shop/t/106/assets/variant-picker.js?v=76420659568485159641776431923

js lorenacanals.com collected 2026-10-03 22:17:34 UTC 14,939 bytes, 2 lines download raw bytes

1import{Component}from"@theme/component";import{VariantSelectedEvent,VariantUpdateEvent}from"@theme/events";import{morph,MORPH_OPTIONS}from"@theme/morph";import{yieldToMainThread,getViewParameterValue,ResizeNotifier}from"@theme/utilities";export default class VariantPicker extends Component{#responseCache=new Map;#prefetchedUrls=new Set;#pendingRequestUrl;#abortController;#checkedIndices=[];#radios=[];#resizeObserver=new ResizeNotifier(()=>this.updateVariantPickerCss());#prefetchTimeout;connectedCallback(){super.connectedCallback(),(this.refs.fieldsets||[]).forEach(fieldset=>{const radios=Array.from(fieldset?.querySelectorAll("input")??[]);this.#radios.push(radios);const initialCheckedIndex=radios.findIndex(radio=>radio.dataset.currentChecked==="true");initialCheckedIndex!==-1&&this.#checkedIndices.push([initialCheckedIndex])}),this.addEventListener("change",this.variantChanged.bind(this)),this.#resizeObserver.observe(this),this.#prefetchTimeout=window.setTimeout(()=>{this.#prefetchFirstSelectorUrls()},0)}disconnectedCallback(){super.disconnectedCallback(),this.#resizeObserver.disconnect(),this.#prefetchTimeout&&window.clearTimeout(this.#prefetchTimeout)}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"),isCalcProduct=this.dataset.calcProduct==="true",currentUrl=this.dataset.productUrl?.split("?")[0],newUrl=selectedOption.dataset.connectedProductUrl,loadsNewProduct=isOnProductPage&&!!newUrl&&newUrl!==currentUrl,isOnFeaturedProductSection=!!this.closest("featured-product-information"),morphElementSelector=loadsNewProduct&&!isCalcProduct?"main":isOnFeaturedProductSection?"featured-product-information":void 0;this.fetchUpdatedSection(this.buildRequestUrl(selectedOption),morphElementSelector);const url=new URL(window.location.href),variantId=selectedOption.dataset.variantId||null;isOnProductPage&&(variantId?url.searchParams.set("variant",variantId):url.searchParams.delete("variant")),loadsNewProduct&&!isCalcProduct&&(url.pathname=newUrl),url.href!==window.location.href&&yieldToMainThread().then(()=>{history.replaceState({},"",url.toString())})}#getFieldsetMeasurements(fieldsetIndex){const fieldset=(this.refs.fieldsets||[])[fieldsetIndex],checkedIndices=this.#checkedIndices[fieldsetIndex],radios=this.#radios[fieldsetIndex];if(!radios||!checkedIndices||!fieldset)return null;const[currentIndex,previousIndex]=checkedIndices;return{fieldset,currentIndex,previousIndex,currentWidth:currentIndex!==void 0?radios[currentIndex]?.parentElement?.offsetWidth:void 0,previousWidth:previousIndex!==void 0?radios[previousIndex]?.parentElement?.offsetWidth:void 0}}#applyFieldsetMeasurements({fieldset,currentWidth,previousWidth,currentIndex,previousIndex}){currentWidth?fieldset.style.setProperty("--pill-width-current",`${currentWidth}px`):currentIndex!==void 0&&fieldset.style.removeProperty("--pill-width-current"),previousWidth?fieldset.style.setProperty("--pill-width-previous",`${previousWidth}px`):previousIndex!==void 0&&fieldset.style.removeProperty("--pill-width-previous")}updateFieldsetCss(fieldsetIndex){if(Number.isNaN(fieldsetIndex))return;const measurements=this.#getFieldsetMeasurements(fieldsetIndex);measurements&&this.#applyFieldsetMeasurements(measurements)}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){const fieldsetIndex=Number.parseInt(target.dataset.fieldsetIndex||""),inputIndex=Number.parseInt(target.dataset.inputIndex||"");if(!Number.isNaN(fieldsetIndex)&&!Number.isNaN(inputIndex)){const fieldset=(this.refs.fieldsets||[])[fieldsetIndex],checkedIndices=this.#checkedIndices[fieldsetIndex],radios=this.#radios[fieldsetIndex];
1if(radios&&checkedIndices&&fieldset){const[currentIndex,previousIndex]=checkedIndices;currentIndex!==void 0&&radios[currentIndex]&&(radios[currentIndex].dataset.previousChecked="false"),previousIndex!==void 0&&radios[previousIndex]&&(radios[previousIndex].dataset.previousChecked="false"),checkedIndices.unshift(inputIndex),checkedIndices.length=Math.min(checkedIndices.length,2);const newCurrentIndex=checkedIndices[0],newPreviousIndex=checkedIndices[1];newCurrentIndex!==void 0&&radios[newCurrentIndex]&&(radios[newCurrentIndex].dataset.currentChecked="true"),newPreviousIndex!==void 0&&radios[newPreviousIndex]&&(radios[newPreviousIndex].dataset.previousChecked="true",radios[newPreviousIndex].dataset.currentChecked="false"),this.updateFieldsetCss(fieldsetIndex)}}target.checked=!0}if(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"),option.selected=!1;newSelectedOption.selected=!0,newSelectedOption.setAttribute("selected","selected")}}#getSelectedOptionElements(){const selectedOptions=[];for(const element of this.querySelectorAll("fieldset, select")){if(element instanceof HTMLFieldSetElement){const checkedInput=element.querySelector("input:checked");checkedInput instanceof HTMLInputElement&&selectedOptions.push(checkedInput);continue}if(!(element instanceof HTMLSelectElement))continue;const selectedOption=element.selectedOptions[0]||element.options[element.selectedIndex];selectedOption instanceof HTMLOptionElement&&selectedOptions.push(selectedOption)}return selectedOptions}#syncSelectState(){for(const select of this.querySelectorAll("select")){if(!(select instanceof HTMLSelectElement))continue;const selectedOption=select.selectedOptions[0]||select.options[select.selectedIndex];for(const option of select.options)option.removeAttribute("selected");selectedOption instanceof HTMLOptionElement&&(selectedOption.selected=!0,selectedOption.setAttribute("selected","selected"))}}buildRequestUrl(selectedOption,source=null,sourceSelectedOptionsValues=[]){let productUrl=selectedOption.dataset.connectedProductUrl||this.#pendingRequestUrl||this.dataset.productUrl;this.#pendingRequestUrl=productUrl;const params=[],viewParamValue=getViewParameterValue();if(viewParamValue&&params.push(`view=${viewParamValue}`),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.dataset.calcProduct==="true"&&this.dataset.templateProductMatch==="true"&&!!this.dataset.sectionId)return productUrl?.includes("?")&&(productUrl=productUrl.split("?")[0]),`${productUrl}?section_id=${this.dataset.sectionId}&${params.join("&")}`;const SECTION_ID_MAP={"quick-add-component":"section-rendering-product-card","swatches-variant-picker-component":"section-rendering-product-card","featured-product-information":this.closest("featured-product-information")?.id},closestSectionId=Object.keys(SECTION_ID_MAP).find(sectionId=>this.closest(sectionId));return closestSectionId?(productUrl?.includes("?")&&(productUrl=productUrl.split("?")[0]),`${productUrl}?section_id=${SECTION_ID_MAP[closestSectionId]}&${params.join("&")}`):`${productUrl}?${params.join("&")}`}fetchUpdatedSection(requestUrl,morphElementSelector){const cachedResponse=this.#responseCache.get(requestUrl);if(cachedResponse){this.#pendingRequestUrl=void 0,this.#handleSectionResponse(cachedResponse,morphElementSelector);return}this.#abortController?.abort(),this.#abortController=new AbortController,fetch(requestUrl,{signal:this.#abortController.signal}).then(response=>response.text()).then(responseText=>{this.#pendingRequestUrl=void 0,this.#responseCache.set(requestUrl,responseText),this.#handleSectionResponse(responseText,morphElementSelector)}).catch(error=>{error.name==="AbortError"?console.warn("Fetch aborted by user"):console.error(error)})}#handleSectionResponse(responseText,morphElementSelector){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)return;const variantResource=JSON.parse(textContent);if(morphElementSelector==="main")this.updateMain(html);else if(morphElementSelector)this.updateElement(html,morphElementSelector);else{const{newProduct,selectionCorrected}
1=this.updateVariantPicker(html,variantResource);if(selectionCorrected)return;this.selectedOptionId&&this.dispatchEvent(new VariantUpdateEvent(variantResource,this.selectedOptionId,{html,productId:this.dataset.productId??"",newProduct}))}}#prefetchFirstSelectorUrls(){if(!(this.dataset.calcProduct!=="true"||this.dataset.templateProductMatch!=="true"))for(const requestUrl of this.#getPrefetchRequestUrls())this.#prefetchedUrls.has(requestUrl)||this.#responseCache.has(requestUrl)||(this.#prefetchedUrls.add(requestUrl),fetch(requestUrl).then(response=>response.text()).then(responseText=>{this.#responseCache.set(requestUrl,responseText)}).catch(()=>{this.#prefetchedUrls.delete(requestUrl)}))}#getPrefetchRequestUrls(){const firstControl=this.querySelector('fieldset[ref="fieldsets[]"], select');if(!firstControl)return[];const urls=[];if(firstControl instanceof HTMLFieldSetElement){for(const input of firstControl.querySelectorAll("input[data-option-value-id]"))input instanceof HTMLInputElement&&(input.checked||urls.push(this.buildRequestUrl(input)));return[...new Set(urls)]}if(!(firstControl instanceof HTMLSelectElement))return[];for(const option of firstControl.options)option instanceof HTMLOptionElement&&(option.selected||urls.push(this.buildRequestUrl(option)));return[...new Set(urls)]}updateVariantPicker(newHtml,variantResource){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}morph(this,newVariantPickerSource,{...MORPH_OPTIONS,getNodeKey:node=>node instanceof HTMLElement?node.dataset.key:void 0}),this.#syncPostMorphState();const selectionCorrected=this.#reconcilePostMorphSelection(variantResource);return selectionCorrected?{newProduct,selectionCorrected}:(this.updateVariantPickerCss(),{newProduct,selectionCorrected})}#syncPostMorphState(){const fieldsets=Array.from(this.querySelectorAll('fieldset[ref="fieldsets[]"]'));this.#radios=[],this.#checkedIndices=[],fieldsets.forEach(fieldset=>{const radios=Array.from(fieldset.querySelectorAll("input")),checkedIndex=radios.findIndex(radio=>radio.checked);radios.forEach((radio,index)=>{radio.dataset.currentChecked=index===checkedIndex?"true":"false",radio.dataset.previousChecked="false"}),this.#radios.push(radios),this.#checkedIndices.push(checkedIndex===-1?[]:[checkedIndex])}),this.#syncSelectState()}#reconcilePostMorphSelection(variantResource){const correction=this.#findSelectionCorrection(variantResource);return correction?(queueMicrotask(()=>{if(correction instanceof HTMLInputElement){correction.checked=!0,correction.dispatchEvent(new Event("change",{bubbles:!0}));return}const firstOption=correction.options[0];if(firstOption){for(const option of correction.options)option.removeAttribute("selected"),option.selected=!1;firstOption.selected=!0,firstOption.setAttribute("selected","selected"),correction.value=firstOption.value,correction.dispatchEvent(new Event("change",{bubbles:!0}))}}),!0):!1}#findSelectionCorrection(variantResource){for(const fieldset of this.querySelectorAll('fieldset[ref="fieldsets[]"]')){if(!(fieldset instanceof HTMLFieldSetElement))continue;const checked=fieldset.querySelector("input:checked");if(checked instanceof HTMLInputElement&&checked.dataset.optionAvailable!=="false")continue;const firstAvailable=fieldset.querySelector('input[data-option-available="true"]');if(firstAvailable instanceof HTMLInputElement&&firstAvailable!==checked)return firstAvailable}for(const select of this.querySelectorAll("select"))if(select instanceof HTMLSelectElement&&select.options.length!==0&&(select.selectedIndex===-1||!select.selectedOptions[0]))return select;if(variantResource==null){const dropdowns=Array.from(this.querySelectorAll("select")).filter(select=>select instanceof HTMLSelectElement&&select.options.length>0),lastSelect=dropdowns[dropdowns.length-1];if(lastSelect instanceof HTMLSelectElement){const firstOption=lastSelect.options[0],selectedOption=lastSelect.selectedOptions[0]||lastSelect.options[lastSelect.selectedIndex];if(firstOption&&selectedOption?.value!==firstOption.value)return lastSelect}}return null}updateVariantPickerCss(){const measurements=(this.refs.fieldsets||[]).map((_,index)=>this.#getFieldsetMeasurements(index)).filter(m=>m!==null);for(const measurement of measurements)this.#applyFieldsetMeasurements(measurement)}updateElement(newHtml,elementSelector){const element=this.closest(elementSelector),newElement=newHtml.querySelector(elementSelector);if(!element||!newElement)throw new Error(`No new element source found for ${elementSelector}`);morph(element,newElement)}updateMain(newHtml){const main=document.querySelector("main"),newMain=newHtml.querySelector("main");
1if(!main||!newMain)throw new Error("No new main source found");morph(main,newMain)}get selectedOption(){const selectedOption=this.#getSelectedOptionElements()[0];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 this.#getSelectedOptionElements().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);
2//# sourceMappingURL=/cdn/shop/t/106/assets/variant-picker.js.map?v=76420659568485159641776431923

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.