1import*as NextSkyTheme from"@NextSkyTheme/global";import{LazyLoader}from"@NextSkyTheme/lazy-load";import{notifier,notifierInline}from"@NextSkyTheme/notification";import{eventModal}from"@NextSkyTheme/modal";export class ProductForm extends HTMLElement{constructor(){super(),this.form=this.querySelector("form"),this.cart=document.querySelector("cart-drawer")||document.querySelector("main-cart"),this.quickView=document.querySelector("quickview-drawer"),this.boughtTogether=document.querySelector("bought-together-popup"),this.shopifyShopableVideo=document.querySelector(".modal-shopable-video"),this.form&&(this.form.querySelector("[name=id]")&&(this.form.querySelector("[name=id]").disabled=!1),this.form.addEventListener("submit",this.onSubmitHandler.bind(this)),this.cart&&this.submitButton&&this.submitButton.setAttribute("aria-haspopup","dialog"),this.hideErrors=this.dataset.hideErrors==="true")}get submitButton(){const cached=this._submitButton;return cached&&cached.isConnected&&this.contains(cached)?cached:this.querySelector('[type="submit"]')}set submitButton(node){this._submitButton=node}get addActionAddCartDesktop(){return this.cart&&this.cart.hasAttribute("data-action-add-cart-desktop")?this.cart.getAttribute("data-action-add-cart-desktop"):"page"}onSubmitHandler(event){event.preventDefault();const submitButton=this.submitButton;if(!submitButton)return;if(submitButton.getAttribute("data-variant-pending")==="true"){this.submitQueued=!0,submitButton.classList.add("loading");return}if(submitButton.getAttribute("aria-disabled")==="true"){this.resetSubmitButtonState(submitButton);return}this.submitQueued=!1,this.error=!1,this.handleErrorMessage(),submitButton.setAttribute("aria-disabled",!0),submitButton.classList.add("loading");const config=NextSkyTheme.fetchConfig("javascript");config.headers["X-Requested-With"]="XMLHttpRequest",delete config.headers["Content-Type"];const formData=new FormData(this.form);this.cart&&(formData.append("sections",this.cart.getSectionsToRender().map(section=>section.id)),formData.append("sections_url",window.location.pathname+window.location.search),NextSkyTheme.global.rootToFocus=submitButton),config.body=formData,fetch(`${routes.cart_add_url}`,config).then(response=>response.json()).then(response=>{if(response.status){NextSkyTheme.publish(NextSkyTheme.PUB_SUB_EVENTS.cartError,{source:"product-form",productVariantId:formData.get("id"),errors:response.errors||response.description,message:response.message}),this.querySelector(".product-form__error-message-wrapper")?this.handleErrorMessage(response.description):notifier.show(response.description,"error",4e3);const soldOutMessage=submitButton.querySelector(".sold-out-message");if(!soldOutMessage)return;submitButton.setAttribute("aria-disabled",!0),submitButton.querySelector("span")?.classList.add("hidden"),soldOutMessage.classList.remove("hidden"),this.error=!0;return}else if(window.innerWidth>767&&(!this.cart||this.addActionAddCartDesktop=="page"||document.body.classList.contains("template-cart"))){window.location=window.routes.cart_url;return}if(this.error||NextSkyTheme.publish(NextSkyTheme.PUB_SUB_EVENTS.cartUpdate,{source:"product-form",productVariantId:formData.get("id"),cartData:response}),this.error=!1,document.body.classList.contains("template-cart")){window.location=window.routes.cart_url;return}else{let focusTargetAfterAdd=submitButton;submitButton.closest("cart-drawer")&&(focusTargetAfterAdd=this.cart.querySelector(".drawer__footer-bottom")),this.cart.renderContents(response);const actionMobile=themeGlobalVariables.settings.actionAddCartMobile;let getCookieCartMessage=!0;if(actionMobile=="cart_message"&&(getCookieCartMessage=NextSkyTheme.getCookie("cart_message"),getCookieCartMessage||NextSkyTheme.setCookie("cart_message","true",1)),document.querySelector("outfit-popup")&&eventModal(document.querySelector("outfit-popup"),"close",!1),document.querySelector("quick-add-popup")&&eventModal(document.querySelector("quick-add-popup"),"close",!1),window.innerWidth>767||actionMobile=="mini_cart"||!getCookieCartMessage){eventModal(this.cart,"open",!1,"delay"),document.querySelector("quickview-drawer.active")&&eventModal(this.quickView,"close",!1),document.querySelector(".modal-shopable-video.active")&&eventModal(this.shopifyShopableVideo,"close",!1),document.querySelector("bought-together-popup.active")&&(eventMod
1al(this.boughtTogether,"close",!1),this.boughtTogether.querySelectorAll(".bought-together-checkbox[type='checkbox']").forEach(item=>{item.checked=!0}),this.recalculateBoughtTogetherTotal());const beforeYouLeave=document.querySelector("before-you-leave.active");beforeYouLeave&&(eventModal(beforeYouLeave,"close",!1),NextSkyTheme.setCookie&&NextSkyTheme.setCookie("before_you_leave_hidden","true",1))}else notifier.showElement(window.cartStrings.addSuccessMobile,null,"success",2500)}}).catch(e=>{console.error(e)}).finally(()=>{new NextSkyTheme.FSProgressBar("free-ship-progress-bar"),this.resetSubmitButtonState(submitButton,this.submitButton),document.dispatchEvent(new CustomEvent("nextsky:cart:added"))})}resetSubmitButtonState(...buttons){new Set(buttons).forEach(button=>{button&&button.getAttribute("data-variant-pending")!=="true"&&(button.classList.remove("loading"),button.querySelectorAll(".hidden-on-load, .btn-label").forEach(label=>label.classList.remove("opacity-0")),this.error||button.removeAttribute("aria-disabled"))})}handleErrorMessage(errorMessage=!1){this.hideErrors||(this.errorMessageWrapper=this.errorMessageWrapper||this.querySelector(".product-form__error-message-wrapper"),this.errorMessageWrapper&&(this.errorMessage=this.errorMessage||this.errorMessageWrapper.querySelector(".product-form__error-message"),this.errorMessageWrapper.toggleAttribute("hidden",!errorMessage),errorMessage&&(this.errorMessage.textContent=errorMessage)))}clearCartErrors(){["cart-errors","CartDrawer-CartErrors","cart-errors-mobile"].forEach(id=>{const box=document.getElementById(id);box&&(box.textContent="")})}refreshCartUI(){const cart=this.cart;return!cart||typeof cart.refresh!="function"?Promise.resolve():cart.refresh()}getSectionsToRender(){return[{id:this.cart.sectionId,section:this.cart.sectionId,selector:".drawer__header-cart"},{id:"cart-icon-bubble",section:"cart-icon-bubble"},{id:this.cart.sectionId,section:this.cart.sectionId,selector:".free-shipping-bar"},{id:this.cart.sectionId,section:this.cart.sectionId,selector:".cart-drawer__form"},{id:this.cart.sectionId,section:this.cart.sectionId,selector:".drawer__footer-bottom-total"}]}updateQuantity(line,quantity,name){this.cart.classList.add("cart-update"),this.clearCartErrors(),this.addLoading(line,!0);const body=JSON.stringify({line,quantity,sections:this.getSectionsToRender().map(section=>section.section),sections_url:window.location.pathname+window.location.search});return fetch(`${routes.cart_change_url}`,{...NextSkyTheme.fetchConfig(),body}).then(response=>response.text()).then(state=>{const parsedState=JSON.parse(state);if(parsedState.errors){const quantity__input=(document.getElementById(`CartItem-${line}`)||document.getElementById(`CartDrawer-Item-${line}`))?.querySelector(".quantity__input");quantity__input&&(quantity__input.value=quantity__input.getAttribute("data-cart-quantity")),notifier.show(parsedState.errors,"error",3e3),this.refreshCartUI();return}this.cart.classList.contains("cart-drawer")?this.updateCartDrawer(parsedState):this.cart.classList.contains("main-cart")&&this.updateMainCart(parsedState)}).catch(error=>{console.error("[cart] update failed",error),this.refreshCartUI();const errors=document.getElementById("cart-errors")||document.getElementById("CartDrawer-CartErrors"),errorsMobile=document.getElementById("cart-errors-mobile");errors&&(errors.textContent=window.cartStrings.error),errorsMobile&&(errorsMobile.textContent=window.cartStrings.error)}).finally(()=>{new NextSkyTheme.FSProgressBar("free-ship-progress-bar"),this.cart.classList.remove("cart-update"),this.addLoading(line,!1);const lineItem=document.getElementById(`CartItem-${line}`)||document.getElementById(`CartDrawer-Item-${line}`);lineItem&&lineItem.querySelector(`[name="${name}"]`)&&lineItem.querySelector(`[name="${name}"]`).focus(),quantity===0&&this.removeBundlePurchasedProduct()})}updateQuantityByKey(lineKey,line,quantity,name,shouldRender=!0){if(!lineKey)return Promise.resolve();this.cart.classList.add("cart-update"),this.clearCartErrors(),line&&this.addLoading(line,!0);const body=JSON.stringify({id:lineKey,quantity,sections:this.getSectionsToRender().map(section=>section.section),sections_url:window.location.pathname+window.location.search});
1return fetch(`${routes.cart_change_url}`,{...NextSkyTheme.fetchConfig(),body}).then(response=>response.text()).then(state=>{const parsedState=JSON.parse(state);if(parsedState.errors){const quantity__input=(document.getElementById(`CartItem-${line}`)||document.getElementById(`CartDrawer-Item-${line}`))?.querySelector(".quantity__input");quantity__input&&(quantity__input.value=quantity__input.getAttribute("data-cart-quantity")),notifier.show(parsedState.errors,"error",3e3),this.refreshCartUI();return}shouldRender&&(this.cart.classList.contains("cart-drawer")?this.updateCartDrawer(parsedState):this.cart.classList.contains("main-cart")&&this.updateMainCart(parsedState))}).catch(error=>{console.error("[cart] update failed",error),this.refreshCartUI();const errors=document.getElementById("cart-errors")||document.getElementById("CartDrawer-CartErrors"),errorsMobile=document.getElementById("cart-errors-mobile");errors&&(errors.textContent=window.cartStrings.error),errorsMobile&&(errorsMobile.textContent=window.cartStrings.error)}).finally(()=>{new NextSkyTheme.FSProgressBar("free-ship-progress-bar"),this.cart.classList.remove("cart-update"),line&&this.addLoading(line,!1),quantity===0&&this.removeBundlePurchasedProduct()})}updateQuantitiesByKey(items,quantity,name){if(!Array.isArray(items)||items.length===0)return;const uniqueItems=[],seenKeys=new Set;if(items.forEach(item=>{!item||!item.key||seenKeys.has(item.key)||(seenKeys.add(item.key),uniqueItems.push(item))}),uniqueItems.length===0)return;let chain=Promise.resolve();uniqueItems.forEach((item,index)=>{chain=chain.then(()=>this.updateQuantityByKey(item.key,item.line,quantity,name,index===uniqueItems.length-1))})}removeBundlePurchasedProduct(){const sectionBundle=localStorage.getItem("bundle-section"),sectionId=JSON.parse(sectionBundle);sectionId&§ionId.forEach(id=>{const bundlePurchasedString=localStorage.getItem(`bundle-purchased-products-${id}`),bundlePurchasedProducts=JSON.parse(bundlePurchasedString);if(!bundlePurchasedString||!Array.isArray(bundlePurchasedProducts)||bundlePurchasedProducts.length===0)return;const productId=this.dataset.productId;if(!productId)return;const updatedProducts=bundlePurchasedProducts.filter(id2=>id2!==productId);localStorage.setItem(`bundle-purchased-products-${id}`,JSON.stringify(updatedProducts));const getAfterBundleProducts=localStorage.getItem(`bundle-purchased-products-${id}`),afterBundleProducts=JSON.parse(getAfterBundleProducts),getBundleSettings=localStorage.getItem(`bundle-min-max-${id}`),bundleMin=JSON.parse(getBundleSettings).minimum,discountPills=document.querySelectorAll(".cart-discount__pill");if(discountPills.length>0){const bundleDiscountString=localStorage.getItem("bundle-discount");if(bundleDiscountString){const bundleDiscounts=JSON.parse(bundleDiscountString);Array.isArray(bundleDiscounts)&&bundleDiscounts.length>0&&discountPills.forEach(pill=>{const discountCode=pill.dataset.discountCode;if(discountCode&&bundleDiscounts.includes(discountCode)&&afterBundleProducts.length<bundleMin){const removeDiscountButton=pill.querySelector("remove-discount");removeDiscountButton&&typeof removeDiscountButton.removeDiscount=="function"&&removeDiscountButton.removeDiscount()}})}}})}updateCartDrawer(parsedState){if(!parsedState?.sections?.[this.cart?.sectionId])return this.refreshCartUI();try{return this.applyCartDrawerUpdates(parsedState)}catch(error){return console.error("[cart] drawer render failed",error),this.refreshCartUI()}}applyCartDrawerUpdates(parsedState){if(this.getSectionDOM(parsedState.sections[this.cart.sectionId],".drawer__inner-empty")){const drawerBody=this.getSectionDOM(parsedState.sections[this.cart.sectionId],".drawer__body");this.cart.querySelector(".drawer__body").innerHTML=drawerBody.innerHTML;const sectionElement=document.getElementById("cart-icon-bubble");sectionElement&&(sectionElement.innerHTML=this.cart.getSectionInnerHTML(parsedState.sections["cart-icon-bubble"]),this.cart.updateCartIcon(sectionElement)),new LazyLoader(".image-lazy-load"),NextSkyTheme.trapFocus(this.cart)}
1else this.getSectionsToRender().forEach((section,index)=>{const sectionElement=section.selector?document.querySelector(section.selector):document.getElementById(section.id);if(sectionElement)if(index===1){const nav_bar_id=document.querySelector("#cart-icon-bubble");nav_bar_id&&nav_bar_id.querySelector(".cart-count")&§ionElement.querySelector(".cart-count")&&(nav_bar_id.querySelector(".cart-count").innerHTML=this.getSectionDOM(parsedState.sections[section.id],".cart-count").innerHTML);const nav_bar_mobile_id=document.querySelector("#cart-icon-bubble-mobile");nav_bar_mobile_id&&nav_bar_mobile_id.querySelector(".cart-count")&§ionElement.querySelector(".cart-count")&&(nav_bar_mobile_id.querySelector(".cart-count").innerHTML=this.getSectionDOM(parsedState.sections[section.id],".cart-count").innerHTML)}else if(index===2){const progress=this.getSectionDOM(parsedState.sections[section.id],".progress");if(sectionElement.querySelector(".progress")&§ionElement.querySelector(".progress").setAttribute("data-total-order",progress.getAttribute("data-total-order")),document.querySelector(".drawer__cart-recommendations")){const recommendations=this.cart.getSectionInnerHTML(parsedState.sections[section.id],".drawer__cart-recommendations");document.querySelector(".drawer__cart-recommendations").innerHTML=recommendations}}else sectionElement.innerHTML=this.cart.getSectionInnerHTML(parsedState.sections[section.id],section.selector)})}updateMainCart(parsedState){if(!parsedState?.sections?.[this.cart?.sectionId])return this.refreshCartUI();try{return this.applyMainCartUpdates(parsedState)}catch(error){return console.error("[cart] main cart render failed",error),this.refreshCartUI()}}applyMainCartUpdates(parsedState){if(this.getSectionDOM(parsedState.sections[this.cart.sectionId],".is-empty")){const drawerBody=this.getSectionDOM(parsedState.sections[this.cart.sectionId],".main-cart__wrapper");this.cart.closest(".main-cart__wrapper").innerHTML=drawerBody.innerHTML;const sectionElement=document.getElementById("cart-icon-bubble");sectionElement&&(sectionElement.innerHTML=this.getSectionInnerHTML(parsedState.sections["cart-icon-bubble"]),this.cart.updateCartIcon(sectionElement)),new LazyLoader(".image-lazy-load")}else this.getSectionsToRender().forEach((section,index)=>{const sectionElement=section.selector?document.querySelector(section.selector):document.getElementById(section.id);if(sectionElement)if(index===1){const nav_bar_id=document.getElementById("cart-icon-bubble");nav_bar_id&&nav_bar_id.querySelector(".cart-count")&&(nav_bar_id.querySelector(".cart-count").innerHTML=this.getSectionDOM(parsedState.sections[section.id],".cart-count").innerHTML);const nav_bar_mobile_id=document.getElementById("cart-icon-bubble-mobile");nav_bar_mobile_id&&nav_bar_mobile_id.querySelector(".cart-count")&&(nav_bar_mobile_id.querySelector(".cart-count").innerHTML=this.getSectionDOM(parsedState.sections[section.id],".cart-count").innerHTML)}else if(index===2){const progress=this.getSectionDOM(parsedState.sections[section.id],".progress");sectionElement.querySelector(".progress")&§ionElement.querySelector(".progress").setAttribute("data-total-order",progress.getAttribute("data-total-order"))}else{sectionElement.innerHTML=this.getSectionInnerHTML(parsedState.sections[section.id],section.selector);const checkout__sticky=this.cart.querySelector(".checkout__sticky__wrapper");checkout__sticky&&(checkout__sticky.innerHTML=this.getSectionDOM(parsedState.sections[section.id],".checkout__sticky__wrapper").innerHTML)}})}getSectionInnerHTML(html,selector=".shopify-section"){return new DOMParser().parseFromString(html,"text/html").querySelector(selector).innerHTML}getSectionDOM(html,selector=".shopify-section"){return new DOMParser().parseFromString(html,"text/html").querySelector(selector)}addLoading(line,action=!1){const cartDrawerItemElements=this.cart.querySelector(`#CartDrawer-Item-${line}`)||this.cart.querySelector(`#CartItem-${line}`);cartDrawerItemElements&&(action?cartDrawerItemElements.classList.add("loading"):cartDrawerItemElements.classList.remove("loading"))}recalculateBoughtTogetherTotal(){if(!this.boughtTogether)return;const currentSection=this.boughtTogether;let total_price=Number(currentSection.getAttribute("data-price"));currentSection.querySelectorAll(".bought-together-checkbox[type='checkbox']").forEach(item=>{const variant_select=item.closest(".product__item-js").querySelector("variant-swatch-select select"),productId=item.value;let value_option="";variant_select&&(value_option=variant_select.value);let price=item.getAttribute("data-price");variant_select&&(price=variant_select.options[variant_select.selectedIndex].getAttribute("data-price"));const variant=currentSection.querySelector(`[product-id="${productId}"]`);item.checked&&(total_price=total_price+Number(price),value_option&&(variant.querySelector('input[name="items[][id]"]').value=value_option),variant.querySelectorAll("input").forEach(input=>{input.disabled=!1}))}),currentSection.querySelector(".bought-together-products-form .total-price .price").innerHTML=NextSkyTheme.formatMoney(total_price,cartStrings.money_format);const totalElementMobile=document.querySelector("button-bought-together-mobile .total-price .price");totalElementMobile&&(totalElementMobile.innerHTML=NextSkyTheme.formatMoney(total_price,cartStrings.money_format))}}customElements.get("product-form")||customElements.define("product-form",ProductForm);class CartRemoveButton extends ProductForm{constructor(){super(),this.addEventListener("click",event=>{event.preventDefault();const embroideryId=(this.dataset.embroideryId||"").trim();if(embroideryId){const escapedId=window.CSS&&window.CSS.escape?window.CSS.escape(embroideryId):embroideryId.replace(/"/g,'\\"'),currentIndex=Number(this.dataset.index),currentKey=this.dataset.key,matchingButtons=Array.from(document.querySelectorAll(`cart-remove-button[data-embroidery-id="${escapedId}"]`)),items=[{key:currentKey,line:Number.isFinite(currentIndex)?currentIndex:null},...matchingButtons.map(button=>({key:button.dataset.key,line:Number(button.dataset.index)}))];if(items.some(item=>item&&item.key)){this.updateQuantitiesByKey(items,0);return}}if(this.dataset.key){this.updateQuantityByKey(this.dataset.key,this.dataset.index,0);return}this.updateQuantity(this.dataset.index,0)})}}customElements.get("cart-remove-button")||customElements.define("cart-remove-button",CartRemoveButton);class MainCartRemoveButton extends ProductForm{constructor(){super(),this.addEventListener("click",event=>{event.preventDefault();const embroideryId=(this.dataset.embroideryId||"").trim();if(embroideryId){const escapedId=window.CSS&&window.CSS.escape?window.CSS.escape(embroideryId):embroideryId.replace(/"/g,'\\"'),currentIndex=Number(this.dataset.index),currentKey=this.dataset.key,matchingButtons=Array.from(document.querySelectorAll(`main-cart-remove-button[data-embroidery-id="${escapedId}"]`)),items=[{key:currentKey,line:Number.isFinite(currentIndex)?currentIndex:null},...matchingButtons.map(button=>({key:button.dataset.key,line:Number(button.dataset.index)}))];if(items.some(item=>item&&item.key)){this.updateQuantitiesByKey(items,0);return}}if(this.dataset.key){this.updateQuantityByKey(this.dataset.key,this.dataset.index,0);return}this.updateQuantity(this.dataset.index,0)})}get sectionId(){return this.closest(".main-cart").getAttribute("data-section-id")}getSectionsToRender(){return[{id:this.sectionId,section:this.sectionId,selector:".main-cart-items"},{id:"cart-icon-bubble",section:"cart-icon-bubble"},{id:this.sectionId,section:this.sectionId,selector:".free-shipping-bar"},{id:this.sectionId,section:this.sectionId,selector:".cart-info .totals"},{id:this.sectionId,section:this.sectionId,selector:".cart-recommendations"},{id:this.sectionId,section:this.sectionId,selector:".cart-discount__codes"}]}updateQuantity(line,quantity,name){this.addLoading(line,!0);const body=JSON.stringify({line,quantity,sections:this.getSectionsToRender().map(section=>section.section),sections_url:window.location.pathname+window.location.search});
1fetch(`${routes.cart_change_url}`,{...NextSkyTheme.fetchConfig(),body}).then(response=>response.text()).then(state=>{const parsedState=JSON.parse(state);if(parsedState.errors){const quantity__input=(document.getElementById(`CartItem-${line}`)||document.getElementById(`CartDrawer-Item-${line}`))?.querySelector(".quantity__input");quantity__input&&(quantity__input.value=quantity__input.getAttribute("data-cart-quantity")),notifier.show(parsedState.errors,"error",3e3),this.refreshCartUI();return}this.cart.classList.contains("cart-drawer")?this.updateCartDrawer(parsedState):this.cart.classList.contains("main-cart")&&this.updateMainCart(parsedState)}).catch(error=>{console.error("[cart] update failed",error),this.refreshCartUI();const errors=document.getElementById("cart-errors")||document.getElementById("CartDrawer-CartErrors"),errorsMobile=document.getElementById("cart-errors-mobile");errors&&(errors.textContent=window.cartStrings.error),errorsMobile&&(errorsMobile.textContent=window.cartStrings.error)}).finally(()=>{new NextSkyTheme.FSProgressBar("free-ship-progress-bar"),this.addLoading(line,!1);const lineItem=document.getElementById(`CartItem-${line}`)||document.getElementById(`CartDrawer-Item-${line}`);lineItem&&lineItem.querySelector(`[name="${name}"]`)&&lineItem.querySelector(`[name="${name}"]`).focus(),quantity===0&&this.removeBundlePurchasedProduct(),fetch(`${routes.cart_url}.js`,{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"}}).then(response=>response.json()).then(cart=>{if(document.querySelector(".cart-page")&&cart.item_count===0){const backToTopDiscount=document.querySelector(".back-top-discount"),offsetHeight=document.querySelector(".checkout__sticky__wrapper").offsetHeight||0;backToTopDiscount&&(backToTopDiscount.style.bottom=offsetHeight+10+"px");const footerBottom=document.querySelector(".footer__bottom");footerBottom&&(footerBottom.style.paddingBottom="0px")}})})}removeBundlePurchasedProduct(){const sectionBundle=localStorage.getItem("bundle-section"),sectionId=JSON.parse(sectionBundle);sectionId&§ionId.forEach(id=>{const bundlePurchasedString=localStorage.getItem(`bundle-purchased-products-${id}`),bundlePurchasedProducts=JSON.parse(bundlePurchasedString);if(!bundlePurchasedString||!Array.isArray(bundlePurchasedProducts)||bundlePurchasedProducts.length===0)return;const productId=this.dataset.productId;if(!productId)return;const updatedProducts=bundlePurchasedProducts.filter(id2=>id2!==productId);localStorage.setItem(`bundle-purchased-products-${id}`,JSON.stringify(updatedProducts));const getAfterBundleProducts=localStorage.getItem(`bundle-purchased-products-${id}`),afterBundleProducts=JSON.parse(getAfterBundleProducts),getBundleSettings=localStorage.getItem(`bundle-min-max-${id}`),bundleMin=JSON.parse(getBundleSettings).minimum,discountPills=document.querySelectorAll(".cart-discount__pill");if(discountPills.length>0){const bundleDiscountString=localStorage.getItem("bundle-discount");if(bundleDiscountString){const bundleDiscounts=JSON.parse(bundleDiscountString);Array.isArray(bundleDiscounts)&&bundleDiscounts.length>0&&discountPills.forEach(pill=>{const discountCode=pill.dataset.discountCode;if(discountCode&&bundleDiscounts.includes(discountCode)&&afterBundleProducts.length<bundleMin){const removeDiscountButton=pill.querySelector("remove-discount");removeDiscountButton&&typeof removeDiscountButton.removeDiscount=="function"&&removeDiscountButton.removeDiscount()}})}}})}}customElements.get("main-cart-remove-button")||customElements.define("main-cart-remove-button",MainCartRemoveButton);class CartItems extends ProductForm{constructor(){super();const debouncedOnChange=NextSkyTheme.debounce(event=>{this.onChange(event)},500);this.addEventListener("change",debouncedOnChange.bind(this))}getSectionsToRender(){return[{id:this.cart.sectionId,section:this.cart.sectionId,selector:".drawer__header-cart"},{id:"cart-icon-bubble",section:"cart-icon-bubble"},{id:this.cart.sectionId,section:this.cart.sectionId,selector:".free-shipping-bar"},{id:this.cart.sectionId,section:this.cart.sectionId,selector:".cart-drawer__form"},{id:this.cart.sectionId,section:this.cart.sectionId,selector:".drawer__footer-bottom-total"}]}onChange(event){const quantity=event.target.value,name=document.activeElement.getAttribute("name"),quantityInput=event.target.closest("quantity-input"),lineKey=event.target.dataset.key,embroideryId=(quantityInput?.dataset.embroideryId||"").trim();if(embroideryId){const escapedId=window.CSS&&window.CSS.escape?window.CSS.escape(embroideryId):embroideryId.replace(/"/g,'\\"'),indexes=Array.from(document.querySelectorAll(`quantity-input[data-embroidery-id="${escapedId}"] input[data-index]`)).map(input=>Number(input.dataset.index)).filter(index=>Number.isFinite(index));if(indexes.length){const items=Array.from(document.querySelectorAll(`quantity-input[data-embroidery-id="${escapedId}"] input[data-index]`)).map(input=>({key:input.dataset.key,line:Number(input.dataset.index)}));if(items.some(item=>item.key)){this.updateQuantitiesByKey(items,quantity,name);return}
1indexes.forEach(line=>this.updateQuantity(line,quantity,name));return}}if(lineKey){this.updateQuantityByKey(lineKey,event.target.dataset.index,quantity,name);return}this.updateQuantity(event.target.dataset.index,quantity,name)}}customElements.get("cart-items")||customElements.define("cart-items",CartItems);class MainCartItems extends ProductForm{constructor(){super();const debouncedOnChange=NextSkyTheme.debounce(event=>{this.onChange(event)},300);this.addEventListener("change",debouncedOnChange.bind(this))}get sectionId(){return this.closest(".main-cart").getAttribute("data-section-id")}getSectionsToRender(){return[{id:this.sectionId,section:this.sectionId,selector:".main-cart-items"},{id:"cart-icon-bubble",section:"cart-icon-bubble"},{id:this.sectionId,section:this.sectionId,selector:".free-shipping-bar"},{id:this.sectionId,section:this.sectionId,selector:".cart-info .totals"},{id:this.sectionId,section:this.sectionId,selector:".cart-recommendations"}]}onChange(event){const quantity=event.target.value,name=document.activeElement.getAttribute("name"),quantityInput=event.target.closest("quantity-input"),lineKey=event.target.dataset.key,embroideryId=(quantityInput?.dataset.embroideryId||"").trim();if(embroideryId){const escapedId=window.CSS&&window.CSS.escape?window.CSS.escape(embroideryId):embroideryId.replace(/"/g,'\\"'),indexes=Array.from(document.querySelectorAll(`quantity-input[data-embroidery-id="${escapedId}"] input[data-index]`)).map(input=>Number(input.dataset.index)).filter(index=>Number.isFinite(index));if(indexes.length){const items=Array.from(document.querySelectorAll(`quantity-input[data-embroidery-id="${escapedId}"] input[data-index]`)).map(input=>({key:input.dataset.key,line:Number(input.dataset.index)}));if(items.some(item=>item.key)){this.updateQuantitiesByKey(items,quantity,name);return}indexes.forEach(line=>this.updateQuantity(line,quantity,name));return}}if(lineKey){this.updateQuantityByKey(lineKey,event.target.dataset.index,quantity,name);return}this.updateQuantity(event.target.dataset.index,quantity,name)}}customElements.get("main-cart-items")||customElements.define("main-cart-items",MainCartItems);class CartGiftWrap extends HTMLElement{constructor(){super()}get cartActionId(){return this.querySelector(".select-package")||null}get cartActionAddons(){return this.querySelector(".toggle-addons")||null}get cartContentAddons(){return this.querySelector(".cart-addons-content")}get cart(){return document.querySelector("cart-drawer")?document.querySelector("cart-drawer"):document.querySelector("main-cart")}connectedCallback(){this.cartActionId&&this.cartActionId.addEventListener("click",this.addGiftWrapClick.bind(this)),this.cartActionAddons&&this.cartActionAddons.addEventListener("click",this.handleGiftWrapToggle.bind(this))}addGiftWrapClick(event){if(event.preventDefault(),this.querySelector('input[type="radio"]:checked')){const variant_id=this.querySelector('input[type="radio"]:checked').value,body=JSON.stringify({id:Number(variant_id),quantity:1,sections:this.cart.getSectionsToRender().map(section=>section.section),sections_url:window.location.pathname+window.location.search});this.cartActionId.classList.add("loading"),fetch(`${routes.cart_add_url}`,{...NextSkyTheme.fetchConfig(),body}).then(response=>response.text()).then(state=>{const parsedState=JSON.parse(state);this.cart.getSectionsToRender().forEach((section,index)=>{const sectionElement=section.selector?document.querySelector(section.selector):document.getElementById(section.id);if(sectionElement)if(index===1){const nav_bar_id=document.querySelector("#cart-icon-bubble");nav_bar_id&&nav_bar_id.querySelector(".cart-count")&&(nav_bar_id.querySelector(".cart-count").innerHTML=this.getSectionDOM(parsedState.sections[section.id],".cart-count").innerHTML);const nav_bar_mobile_id=document.querySelector("#cart-icon-bubble-mobile");nav_bar_mobile_id&&nav_bar_mobile_id.querySelector(".cart-count")&&(nav_bar_mobile_id.querySelector(".cart-count").innerHTML=this.getSectionDOM(parsedState.sections[section.id],".cart-count").innerHTML)}else if(index===2&§ionElement.querySelector(".progress")){const progress=this.getSectionDOM(parsedState.sections[section.id],".progress");sectionElement.querySelector(".progress").setAttribute("data-total-order",progress.getAttribute("data-total-order"))}else sectionElement.innerHTML=this.getSectionInnerHTML(parsedState.sections[section.id],section.selector)})}).catch(()=>{const errors=document.getElementById("cart-errors")||document.getElementById("CartDrawer-CartErrors"),errorsMobile=document.getElementById("cart-errors-mobile");errors&&(errors.textContent=window.cartStrings.error,errorsMobile&&(errorsMobile.textContent=window.cartStrings.error))}).finally(()=>{new NextSkyTheme.FSProgressBar("free-ship-progress-bar"),this.cartActionId.classList.remove("loading"),this.handleGiftWrapToggle()})}}handleGiftWrapToggle(){this.cartContentAddons&&(this.classList.contains("open")?(this.classList.remove("open"),Motion.animate(this.cartContentAddons,{height:0},{duration:.3})):(this.classList.add("open"),Motion.animate(this.cartContentAddons,{height:"auto"},{duration:.3})))}getSectionInnerHTML(html,selector=".shopify-section"){return new DOMParser().parseFromString(html,"text/html").querySelector(selector).innerHTML}getSectionDOM(html,selector=".shopify-section"){return new DOMParser().parseFromString(html,"text/html").querySelector(selector)}}customElements.get("cart-gift-wrap-element")||customElements.define("cart-gift-wrap-element",CartGiftWrap);class CartDiscountElement extends HTMLElement{constructor(){super(),this.cart=document.querySelector("cart-drawer")||document.querySelector("main-cart"),this.observer=null}get cartActionId(){return this.querySelector(".apply-discount")||null}
1get cartActionAddons(){return this.querySelector(".toggle-addons")||null}get cartContentAddons(){return this.querySelector(".cart-addons-content")}connectedCallback(){this.cartActionAddons&&this.cartActionAddons.addEventListener("click",this.handleDiscountToggle.bind(this)),this.cartActionId&&this.cartActionId.addEventListener("click",this.applyDiscount.bind(this));const discountInput=this.querySelector(".cart-discount");discountInput&&discountInput.addEventListener("keydown",event=>{event.key==="Enter"&&(event.preventDefault(),this.applyDiscount(event))}),this.initializeDiscountCodesStyling(),this.setupDiscountObserver()}setupDiscountObserver(){const discountContainer=this.cart.querySelector(".cart-discount__codes")||this.cart;discountContainer&&(this.observer=new MutationObserver(()=>{this.updateFooterAndBackToTop()}),this.observer.observe(discountContainer,{childList:!0,subtree:!0}))}initializeDiscountCodesStyling(){this.updateFooterAndBackToTop(),setTimeout(()=>{this.updateFooterAndBackToTop()},500)}updateFooterAndBackToTop(){if(!document.querySelector(".cart-page"))return;const discountCount=this.existingDiscounts().length,footerBottom=document.querySelector(".footer__bottom");if(footerBottom){const additionalPadding=discountCount*30;footerBottom.style.paddingBottom=`${120+additionalPadding}px`}const backToTopDiscount=document.querySelector(".back-top-discount"),offsetHeight=document.querySelector(".checkout__sticky__wrapper").offsetHeight||0;backToTopDiscount&&(backToTopDiscount.style.bottom=offsetHeight+10+"px")}applyDiscount(event){event.preventDefault(),this.cartActionId.classList.add("loading");const discountCode=this.querySelector(".cart-discount"),discountCodeValue=discountCode.value,notificationContainer=this.closest(".notification-wrapper")||document.querySelector(".notification-wrapper"),discountToBundleString=localStorage.getItem("bundle-discount"),discountToBundle=discountToBundleString?JSON.parse(discountToBundleString):[];if(discountToBundle.length>0&&discountToBundle.includes(discountCodeValue)){this.cartActionId.classList.remove("loading"),notifierInline.show(message.discount.discount_code_error,"error",notificationContainer);return}if(!discountCodeValue){notifierInline.show(message.discount.error,"error",notificationContainer),this.cartActionId.classList.remove("loading");return}const existingDiscounts=this.existingDiscounts(),body=JSON.stringify({discount:[...existingDiscounts,discountCodeValue].join(","),sections:this.cart.dataset.sectionId});fetch(`${routes?.cart_update_url}`,{...NextSkyTheme.fetchConfig(),body}).then(response=>response.json()).then(response=>{if(response.discount_codes.find(discount=>discount.code===discountCodeValue&&discount.applicable===!1)){discountCode.value="",notifierInline.show(message.discount.discount_code_error,"error",notificationContainer);return}const newHtml=response.sections[this.cart.dataset.sectionId];this.renderContent(newHtml),notifierInline.show(message.discount.success,"success",notificationContainer),this.updateFooterAndBackToTop()}).catch(e=>{console.error(e)}).finally(()=>{this.cartActionId.classList.remove("loading")})}renderContent(newHtml){const parsedHtml=new DOMParser().parseFromString(newHtml,"text/html"),updateContent=blockClass=>{const source=parsedHtml.querySelector(`.${blockClass}`),destination=this.cart.querySelector(`.${blockClass}`);if(source&&destination)if(blockClass==="drawer__footer-bottom-total"||blockClass==="main-cart-totals"){const existingDiscountTitles=Array.from(destination.querySelectorAll("li")).map(li=>li.querySelector("div:first-child").textContent.trim());destination.innerHTML=source.innerHTML,destination.querySelectorAll("li").forEach(li=>{const newTitle=li.querySelector("div:first-child").textContent.trim();existingDiscountTitles.includes(newTitle)||li.classList.add("highlight-effect")})}else destination.innerHTML=source.innerHTML};["cart-discount__codes","drawer__footer-bottom-total","checkout__sticky__wrapper","main-cart-totals","cart-content-items"].forEach(updateContent),this.updateFooterAndBackToTop()}existingDiscounts(){const discountCodes=[],discountPills=this.cart.querySelectorAll(".cart-discount__pill");for(const pill of discountPills)pill instanceof HTMLLIElement&&typeof pill.dataset.discountCode=="string"&&discountCodes.push(pill.dataset.discountCode);return discountCodes}handleDiscountToggle(){this.cartContentAddons&&(this.classList.contains("open")?(this.classList.remove("open"),Motion.animate(this.cartContentAddons,{height:0},{duration:.3})):(this.classList.add("open"),Motion.animate(this.cartContentAddons,{height:"auto"},{duration:.3})))}}customElements.get("cart-discount-element")||customElements.define("cart-discount-element",CartDiscountElement);class RemoveDiscount extends CartDiscountElement{constructor(){super(),this.addEventListener("click",event=>{event.preventDefault(),this.removeDiscount()})}removeDiscount(){this.classList.add("loading");
1const wrapper=this.closest(".notification-wrapper");if(wrapper){const notification=wrapper.querySelector(".notification_inline");notification&¬ification.remove()}const discountCode=this.closest(".cart-discount__pill").dataset.discountCode,existingDiscounts=this.closest("cart-discount-element").existingDiscounts(),index=existingDiscounts.indexOf(discountCode);if(index===-1)return;existingDiscounts.splice(index,1);const body=JSON.stringify({discount:[...existingDiscounts].join(","),sections:this.cart.dataset.sectionId});fetch(`${routes?.cart_update_url}`,{...NextSkyTheme.fetchConfig(),body}).then(response=>response.json()).then(response=>{const newHtml=response.sections[this.cart.dataset.sectionId];this.renderContent(newHtml),this.updateFooterAndBackToTop()}).catch(e=>{console.error(e)}).finally(()=>{this.classList.remove("loading")})}}customElements.get("remove-discount")||customElements.define("remove-discount",RemoveDiscount);class CartDrawer extends HTMLElement{constructor(){super()}get cartActionId(){return document.getElementById("cart-icon-bubble")||null}get sectionId(){return this.hasAttribute("data-section-id")?this.getAttribute("data-section-id"):this.getAttribute("data-section-id")}get formAction(){return Array.from(this.querySelectorAll("form .btn"))}get cartViewId(){return document.getElementById("cart-icon-bubble")||null}get openCartMobile(){return this.hasAttribute("data-open-cart-mobile")?this.getAttribute("data-open-cart-mobile"):"popup"}handleTermsAndConditions(){const termsCheckboxes=this.querySelectorAll('input[name="terms_and_conditions"]'),checkoutButtons=this.querySelectorAll('button[name="checkout"]');if(termsCheckboxes.length===0||checkoutButtons.length===0)return;const updateButtonState=(checkbox,button)=>{checkbox.checked?(button.disabled=!1,button.classList.remove("disabled")):(button.disabled=!0,button.classList.add("disabled"))};termsCheckboxes.forEach((checkbox,index)=>{const button=checkoutButtons[index]||checkoutButtons[0];button&&updateButtonState(checkbox,button),checkbox.addEventListener("change",()=>{checkoutButtons.forEach(btn=>{Array.from(termsCheckboxes).some(cb=>cb.checked)?(btn.disabled=!1,btn.classList.remove("disabled")):(btn.disabled=!0,btn.classList.add("disabled"))})})})}connectedCallback(){[document.getElementById("cart-icon-bubble"),document.getElementById("cart-icon-bubble-mobile")].forEach(trigger=>{trigger&&trigger.addEventListener("click",event=>this.onShowCartDrawer(event,trigger))}),this.formAction.forEach(action=>{action.addEventListener("click",event=>{action.classList.add("loading")})}),this.handleTermsAndConditions(),this.openCartMobile=="popup"&&this.innerWidth(),window.Shopify.designMode&&(document.addEventListener("shopify:section:select",event=>{const currentTarget=event.target;JSON.parse(currentTarget.dataset.shopifyEditorSection).id===this.sectionId&&eventModal(this,"open",!1)}),document.addEventListener("shopify:section:deselect",()=>{const drawer=document.querySelector("cart-drawer");drawer&&eventModal(drawer,"close",!1)}))}innerWidth(){let width=window.innerWidth;window.addEventListener("resize",()=>{const newWidth=window.innerWidth;newWidth<=767&&width>767&&this.actionOnMobile(),newWidth>767&&width<=767&&this.actionOutMobile(),width=newWidth}),width<=767?this.actionOnMobile():this.actionOutMobile()}actionOnMobile(){const modal_inner=this.querySelector(".modal-inner");modal_inner.classList.add("modal-draggable"),modal_inner.classList.remove("draw-mb","drawer-right-mb")}actionOutMobile(){const modal_inner=this.querySelector(".modal-inner");modal_inner.classList.remove("modal-draggable"),modal_inner.classList.add("draw-mb","drawer-right-mb")}getSectionsToRender(){return[{id:this.sectionId,section:this.sectionId,selector:".drawer__header-cart"},{id:"cart-icon-bubble",section:"cart-icon-bubble"},{id:this.sectionId,section:this.sectionId,selector:".free-shipping-bar"},{id:this.sectionId,section:this.sectionId,selector:".cart-drawer__form"},{id:this.sectionId,section:this.sectionId,selector:".drawer__footer-bottom-total"}]}renderContents(parsedState){if(!parsedState?.sections?.[this.sectionId])return this.refresh();try{return this.applyRenderContents(parsedState)}catch(error){return console.error("[cart] drawer render failed",error),this.refresh()}}async refresh(){try{const url=new URL(window.location.href);
1url.searchParams.set("sections",`${this.sectionId},cart-icon-bubble`);const data=await fetch(url.toString()).then(response=>response.json()),drawerBody=this.getSectionDOM(data[this.sectionId],".drawer__body"),target=this.querySelector(".drawer__body");drawerBody&&target&&(target.innerHTML=drawerBody.innerHTML,new LazyLoader(".image-lazy-load"));const bubble=document.getElementById("cart-icon-bubble");bubble&&data["cart-icon-bubble"]&&(bubble.innerHTML=this.getSectionInnerHTML(data["cart-icon-bubble"]),this.updateCartIcon(bubble)),new NextSkyTheme.FSProgressBar("free-ship-progress-bar")}catch(error){console.error("[cart] drawer refresh failed",error)}}applyRenderContents(parsedState){if(this.querySelector(".drawer__inner-empty")){const drawerBody=this.getSectionDOM(parsedState.sections[this.sectionId],".drawer__body");this.querySelector(".drawer__body").innerHTML=drawerBody.innerHTML,this.querySelectorAll("form .btn").forEach(action=>{action.addEventListener("click",()=>{action.classList.add("loading")})});const sectionElement=document.getElementById("cart-icon-bubble");sectionElement&&(sectionElement.innerHTML=this.getSectionInnerHTML(parsedState.sections["cart-icon-bubble"]),this.updateCartIcon(sectionElement));return}else this.getSectionsToRender().forEach((section,index)=>{const sectionElement=section.selector?document.querySelector(section.selector):document.getElementById(section.id);if(sectionElement){if(sectionElement.innerHTML=this.getSectionInnerHTML(parsedState.sections[section.id],section.selector),index===1&&this.updateCartIcon(sectionElement),index===2){const progress=this.getSectionDOM(parsedState.sections[section.id],".progress");sectionElement.querySelector(".progress")&§ionElement.querySelector(".progress").setAttribute("data-total-order",progress.getAttribute("data-total-order"))}if(index===3&&document.querySelector(".drawer__cart-recommendations")){const recommendations=this.getSectionInnerHTML(parsedState.sections[section.id],".drawer__cart-recommendations");document.querySelector(".drawer__cart-recommendations").innerHTML=recommendations}}})}updateCartIcon(sectionElement){const nav_bar_id=document.querySelector("#cart-icon-bubble");nav_bar_id&&nav_bar_id.querySelector(".cart-count")&§ionElement.querySelector(".cart-count")&&(nav_bar_id.querySelector(".cart-count").innerHTML=sectionElement.querySelector(".cart-count").innerHTML);const nav_bar_mobile_id=document.querySelector("#cart-icon-bubble-mobile");nav_bar_mobile_id&&nav_bar_mobile_id.querySelector(".cart-count")&§ionElement.querySelector(".cart-count")&&(nav_bar_mobile_id.querySelector(".cart-count").innerHTML=sectionElement.querySelector(".cart-count").innerHTML)}getSectionInnerHTML(html,selector=".shopify-section"){return new DOMParser().parseFromString(html,"text/html").querySelector(selector).innerHTML}getSectionDOM(html,selector=".shopify-section"){return new DOMParser().parseFromString(html,"text/html").querySelector(selector)}onShowCartDrawer(event,triggerEl){event.preventDefault(),eventModal(this,"open",!1,"delay"),NextSkyTheme.global.rootToFocus=triggerEl||this.cartActionId}}customElements.define("cart-drawer",CartDrawer);class MainCart extends HTMLElement{constructor(){super()}get sectionId(){return this.getAttribute("data-section-id")}async refresh(){try{const url=new URL(window.location.href);url.searchParams.set("sections",`${this.sectionId},cart-icon-bubble`);const data=await fetch(url.toString()).then(response=>response.json()),parser=new DOMParser,source=parser.parseFromString(data[this.sectionId],"text/html").querySelector(".main-cart__wrapper"),target=document.querySelector(".main-cart__wrapper");source&&target&&(target.innerHTML=source.innerHTML,new LazyLoader(".image-lazy-load"));const bubble=document.getElementById("cart-icon-bubble");if(bubble&&data["cart-icon-bubble"]){const bubbleSource=parser.parseFromString(data["cart-icon-bubble"],"text/html").querySelector(".shopify-section");bubbleSource&&(bubble.innerHTML=bubbleSource.innerHTML)}new NextSkyTheme.FSProgressBar("free-ship-progress-bar")}catch(error){console.error("[cart] main cart refresh failed",error)}}connectedCallback(){this.handleTermsAndConditions()}handleTermsAndConditions(){const termsCheckboxes=this.querySelectorAll('input[name="terms_and_conditions"]'),
1checkoutButtons=this.querySelectorAll('button[name="checkout"]');if(termsCheckboxes.length===0||checkoutButtons.length===0)return;const updateButtonState=(checkbox,button)=>{checkbox.checked?(button.disabled=!1,button.classList.remove("disabled")):(button.disabled=!0,button.classList.add("disabled"))};termsCheckboxes.forEach((checkbox,index)=>{const button=checkoutButtons[index]||checkoutButtons[0];button&&updateButtonState(checkbox,button),checkbox.addEventListener("change",()=>{checkoutButtons.forEach(btn=>{Array.from(termsCheckboxes).some(cb=>cb.checked)?(btn.disabled=!1,btn.classList.remove("disabled")):(btn.disabled=!0,btn.classList.add("disabled"))})})})}getSectionsToRender(){return[{id:this.sectionId,section:this.sectionId,selector:".main-cart-items"},{id:"cart-icon-bubble",section:"cart-icon-bubble"},{id:this.sectionId,section:this.sectionId,selector:".free-shipping-bar"},{id:this.sectionId,section:this.sectionId,selector:".cart-info .totals"},{id:this.sectionId,section:this.sectionId,selector:".cart-recommendations"}]}}customElements.define("main-cart",MainCart); 2//# sourceMappingURL=/cdn/shop/t/234/assets/module-add-to-cart.js.map?v=112062960890465297341789630092
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.