customElements.get("quick-order-list-remove-button")||customElements.define("quick-order-list-remove-button",class extends HTMLElement{constructor(){super(),this.addEventListener("click",event=>{event.preventDefault(),this.closest("quick-order-list").updateQuantity(this.dataset.index,0)})}}),customElements.get("quick-order-list-remove-all-button")||customElements.define("quick-order-list-remove-all-button",class extends HTMLElement{constructor(){super(),this.quickOrderList=this.closest("quick-order-list");const allVariants=this.quickOrderList.querySelectorAll("[data-quantity-variant-id]"),items={};let hasVariantsInCart=!1;allVariants.forEach(variant=>{parseInt(variant.dataset.cartQuantity)>0&&(hasVariantsInCart=!0,items[parseInt(variant.dataset.quantityVariantId)]=0)}),hasVariantsInCart||this.classList.add("hidden"),this.actions={confirm:"confirm",remove:"remove",cancel:"cancel"},this.addEventListener("click",event=>{event.preventDefault(),this.dataset.action===this.actions.confirm?this.toggleConfirmation(!1,!0):this.dataset.action===this.actions.remove?(this.quickOrderList.updateMultipleQty(items),this.toggleConfirmation(!0,!1)):this.dataset.action===this.actions.cancel&&this.toggleConfirmation(!0,!1)})}toggleConfirmation(showConfirmation,showInfo){this.quickOrderList.querySelector(".quick-order-list-total__confirmation").classList.toggle("hidden",showConfirmation),this.quickOrderList.querySelector(".quick-order-list-total__info").classList.toggle("hidden",showInfo)}}),customElements.get("quick-order-list")||customElements.define("quick-order-list",class extends HTMLElement{constructor(){super(),this.cart=document.querySelector("cart-drawer"),this.actions={add:"ADD",update:"UPDATE"},this.quickOrderListId=`quick-order-list-${this.dataset.productId}`,this.defineInputsAndQuickOrderTable(),this.variantItemStatusElement=document.getElementById("shopping-cart-variant-item-status");const form=this.querySelector("form");this.inputFieldHeight=this.querySelector(".variant-item__quantity-wrapper").offsetHeight,this.isListInsideModal=document.querySelector(".quick-add-bulk"),this.stickyHeaderElement=document.querySelector("sticky-header"),this.getTableHead(),this.getTotalBar(),this.stickyHeaderElement&&(this.stickyHeader={height:this.stickyHeaderElement.offsetHeight,type:`${this.stickyHeaderElement.getAttribute("data-sticky-type")}`}),this.getTotalBar()&&(this.totalBarPosition=window.innerHeight-this.getTotalBar().offsetHeight,window.addEventListener("resize",()=>{this.totalBarPosition=window.innerHeight-this.getTotalBar().offsetHeight,this.stickyHeader.height=this.stickyHeaderElement?this.stickyHeaderElement.offsetHeight:0}));const pageParams=new URLSearchParams(window.location.search);window.pageNumber=decodeURIComponent(pageParams.get("page")||""),form.addEventListener("submit",this.onSubmit.bind(this)),this.addMultipleDebounce()}cartUpdateUnsubscriber=void 0;onSubmit(event){event.preventDefault()}connectedCallback(){this.cartUpdateUnsubscriber=subscribe(PUB_SUB_EVENTS.cartUpdate,event=>{event.source!==this.quickOrderListId&&this.refresh().then(()=>{this.defineInputsAndQuickOrderTable(),this.addMultipleDebounce()})}),this.sectionId=this.dataset.id}disconnectedCallback(){this.cartUpdateUnsubscriber?.()}defineInputsAndQuickOrderTable(){this.allInputsArray=Array.from(this.querySelectorAll('input[type="number"]')),this.quickOrderListTable=this.querySelector(".quick-order-list__table"),this.quickOrderListTable.addEventListener("focusin",this.switchVariants.bind(this))}onChange(event){const inputValue=parseInt(event.target.value),cartQuantity=parseInt(event.target.dataset.cartQuantity),index=event.target.dataset.index,name=document.activeElement.getAttribute("name"),quantity=inputValue-cartQuantity;this.cleanErrorMessageOnType(event),inputValue==0?this.updateQuantity(index,inputValue,name,this.actions.update):this.validateQuantity(event,name,index,inputValue,cartQuantity,quantity)}cleanErrorMessageOnType(event){event.target.addEventListener("keydown",()=>{event.target.setCustomValidity(" "),event.target.reportValidity()})}validateQuantity(event,name,index,inputValue,cartQuantity,quantity){inputValueparseInt(event.target.max)?this.setValidity(event,index,window.quickOrderListStrings.max_error.replace("[max]",event.target.max)):inputValue%parseInt(event.target.step)!=0?this.setValidity(event,index,window.quickOrderListStrings.step_error.replace("[step]",event.target.step)):(event.target.setCustomValidity(""),event.target.reportValidity(),cartQuantity>0?this.updateQuantity(index,inputValue,name,this.actions.update):this.updateQuantity(index,quantity,name,this.actions.add))}setValidity(event,index,message){event.target.setCustomValidity(message),event.target.reportValidity(),this.resetQuantityInput(index),event.target.select()}validateInput(target){return target.max?parseInt(target.value)==0||parseInt(target.value)>=parseInt(target.dataset.min)&&parseInt(target.value)<=parseInt(target.max)&&parseInt(target.value)%parseInt(target.step)==0:parseInt(target.value)==0||parseInt(target.value)>=parseInt(target.dataset.min)&&parseInt(target.value)%parseInt(target.step)==0}refresh(){return new Promise((resolve,reject)=>{fetch(`${this.getSectionsUrl()}?section_id=${this.sectionId}`).then(response=>response.text()).then(responseText=>{const sourceQty=new DOMParser().parseFromString(responseText,"text/html").querySelector(`#${this.quickOrderListId}`);sourceQty&&(this.innerHTML=sourceQty.innerHTML),resolve()}).catch(e=>{console.error(e),reject(e)})})}getSectionsToRender(){return[{id:this.quickOrderListId,section:document.getElementById(this.quickOrderListId).dataset.id,selector:`#${this.quickOrderListId} .js-contents`},{id:"cart-icon-bubble",section:"cart-icon-bubble",selector:".shopify-section"},{id:`quick-order-list-live-region-text-${this.dataset.productId}`,section:"cart-live-region-text",selector:".shopify-section"},{id:`quick-order-list-total-${this.dataset.productId}`,section:document.getElementById(this.quickOrderListId).dataset.id,selector:`#${this.quickOrderListId} .quick-order-list__total`},{id:"CartDrawer",selector:"#CartDrawer",section:"cart-drawer"}]}addMultipleDebounce(){this.querySelectorAll("quantity-input").forEach(qty=>{const debouncedOnChange=debounce(event=>{this.onChange(event)},ON_CHANGE_DEBOUNCE_TIMER);qty.addEventListener("change",debouncedOnChange.bind(this))})}addDebounce(id){const element=this.querySelector(`#Variant-${id} quantity-input`),debouncedOnChange=debounce(event=>{this.onChange(event)},ON_CHANGE_DEBOUNCE_TIMER);element.addEventListener("change",debouncedOnChange.bind(this))}renderSections(parsedState,id){this.getSectionsToRender().forEach(section=>{const sectionElement=document.getElementById(section.id);sectionElement&§ionElement.parentElement&§ionElement.parentElement.classList.contains("drawer")&&(parsedState.items.length>0?sectionElement.parentElement.classList.remove("is-empty"):sectionElement.parentElement.classList.add("is-empty"),setTimeout(()=>{document.querySelector("#CartDrawer-Overlay").addEventListener("click",this.cart.close.bind(this.cart))}));const elementToReplace=sectionElement&§ionElement.querySelector(section.selector)?sectionElement.querySelector(section.selector):sectionElement;elementToReplace&&(section.selector===`#${this.quickOrderListId} .js-contents`&&id!==void 0?elementToReplace.querySelector(`#Variant-${id}`).innerHTML=this.getSectionInnerHTML(parsedState.sections[section.section],`#Variant-${id}`):elementToReplace.innerHTML=this.getSectionInnerHTML(parsedState.sections[section.section],section.selector))}),this.defineInputsAndQuickOrderTable(),id?this.addDebounce(id):this.addMultipleDebounce()}getTableHead(){return document.querySelector(".quick-order-list__table thead")}getTotalBar(){return this.querySelector(".quick-order-list__total")}scrollQuickOrderListTable(){const inputTopBorder=this.variantListInput.getBoundingClientRect().top,inputBottomBorder=this.variantListInput.getBoundingClientRect().bottom;if(this.isListInsideModal){const totalBarCrossesInput=inputBottomBorder>this.getTotalBar().getBoundingClientRect().top,tableHeadCrossesInput=inputTopBorderthis.totalBarPosition,inputOutsideOfViewPort=inputBottomBorderinputTopBorder,stickyHeaderScrollupCrossesInput=this.stickyHeaderElement&&this.stickyHeader.type==="on-scroll-up"&&this.stickyHeader.height>inputTopBorder&&stickyHeaderBottomBorder>0;(totalBarCrossesInput||inputOutsideOfViewPort||stickyHeaderCrossesInput||stickyHeaderScrollupCrossesInput)&&this.scrollToCenter()}}scrollToCenter(){this.variantListInput.scrollIntoView({block:"center",behavior:"smooth"})}switchVariants(event){event.target.tagName==="INPUT"&&(this.variantListInput=event.target,this.variantListInput.select(),this.allInputsArray.length!==1?(this.variantListInput.addEventListener("keydown",e=>{if(e.key==="Enter"&&(e.preventDefault(),e.target.blur(),this.validateInput(e.target))){const currentIndex=this.allInputsArray.indexOf(e.target);if(this.lastKey=e.shiftKey,e.shiftKey){const previousIndex=currentIndex-1,previousVariant=this.allInputsArray[previousIndex]||this.allInputsArray[this.allInputsArray.length-1];this.lastElement=previousVariant.dataset.index,previousVariant.select()}else{const nextIndex=currentIndex+1;(this.allInputsArray[nextIndex]||this.allInputsArray[0]).select()}}}),this.scrollQuickOrderListTable()):this.variantListInput.addEventListener("keydown",e=>{e.key==="Enter"&&(e.preventDefault(),e.target.blur())}))}updateMultipleQty(items){this.querySelector(".variant-remove-total .loading__spinner").classList.remove("hidden");const body=JSON.stringify({updates:items,sections:this.getSectionsToRender().map(section=>section.section),sections_url:this.getSectionsUrl()});this.updateMessage(),this.setErrorMessage(),fetch(`${routes.cart_update_url}`,{...fetchConfig(),body}).then(response=>response.text()).then(state=>{const parsedState=JSON.parse(state);this.renderSections(parsedState)}).catch(()=>{this.setErrorMessage(window.cartStrings.error)}).finally(()=>{this.querySelector(".variant-remove-total .loading__spinner").classList.add("hidden")})}getSectionsUrl(){return window.pageNumber?`${window.location.pathname}?page=${window.pageNumber}`:`${window.location.pathname}`}updateQuantity(id,quantity,name,action){this.toggleLoading(id,!0),this.cleanErrors();let routeUrl=routes.cart_change_url,body=JSON.stringify({quantity,id,sections:this.getSectionsToRender().map(section=>section.section),sections_url:this.getSectionsUrl()}),fetchConfigType;action===this.actions.add&&(fetchConfigType="javascript",routeUrl=routes.cart_add_url,body=JSON.stringify({items:[{quantity:parseInt(quantity),id:parseInt(id)}],sections:this.getSectionsToRender().map(section=>section.section),sections_url:this.getSectionsUrl()})),this.updateMessage(),this.setErrorMessage(),fetch(`${routeUrl}`,{...fetchConfig(fetchConfigType),body}).then(response=>response.text()).then(state=>{const parsedState=JSON.parse(state),quantityElement=document.getElementById(`Quantity-${id}`),items=document.querySelectorAll(".variant-item");if(parsedState.description||parsedState.errors){document.querySelector(`[id^="Variant-${id}"] .variant-item__totals.small-hide .loading__spinner`).classList.add("loading__spinner--error"),this.resetQuantityInput(id,quantityElement),parsedState.errors?this.updateLiveRegions(id,parsedState.errors):this.updateLiveRegions(id,parsedState.description);return}this.classList.toggle("is-empty",parsedState.item_count===0),this.renderSections(parsedState,id);let hasError=!1;const currentItem=parsedState.items.find(item=>item.variant_id===parseInt(id)),updatedValue=currentItem?currentItem.quantity:void 0;updatedValue&&updatedValue!==quantity&&(this.updateError(updatedValue,id),hasError=!0),publish(PUB_SUB_EVENTS.cartUpdate,{source:this.quickOrderListId,cartData:parsedState}),hasError?this.updateMessage():action===this.actions.add?this.updateMessage(parseInt(quantity)):action===this.actions.update?this.updateMessage(parseInt(quantity-quantityElement.dataset.cartQuantity)):this.updateMessage(-parseInt(quantityElement.dataset.cartQuantity))}).catch(error=>{this.querySelectorAll(".loading__spinner").forEach(overlay=>overlay.classList.add("hidden")),this.resetQuantityInput(id),console.error(error),this.setErrorMessage(window.cartStrings.error)}).finally(()=>{this.toggleLoading(id),this.lastKey&&this.lastElement===id&&this.querySelector(`#Variant-${id} input`).select()})}resetQuantityInput(id,quantityElement){const input=quantityElement??document.getElementById(`Quantity-${id}`);input.value=input.getAttribute("value")}setErrorMessage(message=null){this.errorMessageTemplate=this.errorMessageTemplate??document.getElementById(`QuickOrderListErrorTemplate-${this.dataset.productId}`).cloneNode(!0),document.querySelectorAll(".quick-order-list-error").forEach(errorElement=>{if(errorElement.innerHTML="",!message)return;const updatedMessageElement=this.errorMessageTemplate.cloneNode(!0);updatedMessageElement.content.querySelector(".quick-order-list-error-message").innerText=message,errorElement.appendChild(updatedMessageElement.content)})}updateMessage(quantity=null){const messages=this.querySelectorAll(".quick-order-list__message-text"),icons=this.querySelectorAll(".quick-order-list__message-icon");if(quantity===null||isNaN(quantity)){messages.forEach(message=>message.innerHTML=""),icons.forEach(icon=>icon.classList.add("hidden"));return}const isQuantityNegative=quantity<0,absQuantity=Math.abs(quantity),textTemplate=isQuantityNegative?absQuantity===1?window.quickOrderListStrings.itemRemoved:window.quickOrderListStrings.itemsRemoved:quantity===1?window.quickOrderListStrings.itemAdded:window.quickOrderListStrings.itemsAdded;messages.forEach(msg=>msg.innerHTML=textTemplate.replace("[quantity]",absQuantity)),isQuantityNegative||icons.forEach(i=>i.classList.remove("hidden"))}updateError(updatedValue,id){let message="";typeof updatedValue>"u"?message=window.cartStrings.error:message=window.cartStrings.quantityError.replace("[quantity]",updatedValue),this.updateLiveRegions(id,message)}cleanErrors(){this.querySelectorAll(".desktop-row-error").forEach(error=>error.classList.add("hidden")),this.querySelectorAll(".variant-item__error-text").forEach(error=>error.innerHTML="")}updateLiveRegions(id,message){const variantItemErrorDesktop=document.getElementById(`Quick-order-list-item-error-desktop-${id}`),variantItemErrorMobile=document.getElementById(`Quick-order-list-item-error-mobile-${id}`);variantItemErrorDesktop&&(variantItemErrorDesktop.querySelector(".variant-item__error-text").innerHTML=message,variantItemErrorDesktop.closest("tr").classList.remove("hidden")),variantItemErrorMobile&&(variantItemErrorMobile.querySelector(".variant-item__error-text").innerHTML=message),this.variantItemStatusElement.setAttribute("aria-hidden",!0);const cartStatus=document.getElementById("quick-order-list-live-region-text");cartStatus.setAttribute("aria-hidden",!1),setTimeout(()=>{cartStatus.setAttribute("aria-hidden",!0)},1e3)}getSectionInnerHTML(html,selector){return new DOMParser().parseFromString(html,"text/html").querySelector(selector).innerHTML}toggleLoading(id,enable){const quickOrderListItems=this.querySelectorAll(`#Variant-${id} .loading__spinner`),quickOrderListItem=this.querySelector(`#Variant-${id}`);enable?(quickOrderListItem.classList.add("quick-order-list__container--disabled"),[...quickOrderListItems].forEach(overlay=>overlay.classList.remove("hidden")),this.variantItemStatusElement.setAttribute("aria-hidden",!1)):(quickOrderListItem.classList.remove("quick-order-list__container--disabled"),quickOrderListItems.forEach(overlay=>overlay.classList.add("hidden")))}}); //# sourceMappingURL=/cdn/shop/t/11/assets/quick-order-list.js.map?v=43984344682387365861719931490