PageSourceSearch

https://www.crunchlabs.com/cdn/shop/t/704/assets/component-ajax-cart.js?v=18147132924706714981790793055

js crunchlabs.com collected 2026-10-01 11:29:45 UTC 19,116 bytes, 2 lines download raw bytes

1const drawerSelectors={cartIcons:document.querySelectorAll(".header__icon--cart"),cartIconDesktop:document.querySelector("#cart-icon-desktop"),cartIconMobile:document.querySelector("#cart-icon-mobile"),cartDrawerCount:document.querySelector("#cartCount")};Shopify.Cart=Shopify.Cart||{},Shopify.Cart.GiftWrap={},Shopify.Cart.GiftWrap.processGiftWrappingForCartItem=async(id,validateCheckbox,cart=null,productPage=!1)=>{const processItems=(idInput,type,cartData,resolve)=>{let updates=[],itemsResult,subscriptionBoxes=window.globalVariables.cart.items.filter(({product_type=""})=>{const pt=String(product_type).toLowerCase(),isSubscription=pt.includes("subscription");return type==="expedited-shipping"?isSubscription&&!pt.includes("hack"):isSubscription}).reduce((total,{quantity=0})=>total+quantity,0);if(cartData){let currentIWW=document.querySelector(`.items-with-${type}`)?.value;itemsResult=[],[].slice.call(document.querySelectorAll(`.subscription-${type} input[type="checkbox"]`)).map(gwc=>{gwc.checked&&itemsResult.push(gwc.id.replace(`${type}-checkbox-`,""))}),itemsResult.length>0?updates[idInput.value]=subscriptionBoxes:updates[idInput.value]=0,(!currentIWW&&itemsResult.length===0||currentIWW&&currentIWW.split(",").length===itemsResult.length)&&resolve(!1)}else{let checkbox;type==="expedited-shipping"?checkbox=document.querySelector(`[data-item-id="${type}-checkbox-"]`):checkbox=document.querySelector(`#${type}-checkbox-${id}`),checkbox||(checkbox=document.querySelector(`#${type}-checkbox-`)),validateCheckbox&&checkbox?.checked?(productPage&&!checkbox?.dataset?.name?.includes("hack")?updates[idInput.value]=subscriptionBoxes+1:updates[idInput.value]=subscriptionBoxes,type==="expedited-shipping"?itemsResult=["true"]:itemsResult=[""]):(updates[idInput.value]=0,itemsResult=[])}return[updates,itemsResult]};return new Promise(resolve=>{const gwId=document.querySelector(".gift-wrapping-id"),esId=document.querySelector(".expedited-shipping-id");if(gwId&&gwId.value||esId&&esId.value){let[updates,itemsWithWrapping]=processItems(gwId,"gift-wrapping",cart,resolve),[secondUpdates,itemsWithExpedited]=processItems(esId,"expedited-shipping",cart,resolve);const request={method:"POST",headers:new Headers({"Content-Type":"application/json"}),body:JSON.stringify({updates:Object.assign({},{...updates,...secondUpdates}),attributes:{"gift-wrapping":itemsWithWrapping.length>0,"gift-note":"","items-with-expedited-shipping":itemsWithExpedited.length>0?!0:""}})};fetch("/cart/update.js",request).then(response=>response.json()).then(response=>{[].slice.call(document.querySelectorAll(".items-with-gift-wrapping")).map(giww=>{giww.value=itemsWithWrapping.join(",")}),[].slice.call(document.querySelectorAll(".items-with-expedited-shipping")).map(iwes=>{iwes.value=itemsWithExpedited.join(",")}),resolve(response)}).catch(()=>{resolve(!1)})}else resolve(!1)})};class ajaxCart extends HTMLElement{constructor(){super(),this.openeBy=drawerSelectors.cartIcons,this._cartSnapshotFresh=!1,this._exceedsInFlight=!1,window.AddonEligibility&&window.AddonEligibility.ready(),this.bindEvents(),this.cartNoteInput(),this.querySelectorAll(".close-ajax--cart").forEach(button=>button.addEventListener("click",this.closeCartDrawer.bind(this))),window.globalVariables.template!=="cart"?(this.addAccessibilityAttributes(this.openeBy),this.getCartData(""),window.addEventListener("pageshow",event=>{event.persisted&&this.getCartData("")})):this.style.visibility="visible",navigator.platform==="iPhone"&&document.documentElement.style.setProperty("--viewport-height",`${window.innerHeight}px`)}static get observedAttributes(){return["updating"]}attributeChangedCallback(name,oldValue,newValue){name=="updating"&&newValue=="false"&&this.updateEvents()}addAccessibilityAttributes(openDrawerButtons){let _this=this;openDrawerButtons.forEach(element=>{element.setAttribute("role","button"),element.setAttribute("aria-expanded",!1),element.setAttribute("aria-controls",_this.id)})}onKeyUp(event){event.code.toUpperCase()==="ESCAPE"&&this.querySelector(".close-ajax--cart").dispatchEvent(new Event("click"))}bindEvents(){window.globalVariables.template!=="cart"&&(this.openeBy.forEach(cartBtn=>cartBtn.addEventListener("click",this.openCartDrawer.bind(this))),this.addEventListener("keyup",this.onKeyUp.bind(this))),this.updateEvents()}updateEvents(){this.querySelectorAll("[data-itemRemove]").forEach(button=>button.addEventListener("click",this.removeItem.bind(this))),this.querySelectorAll("[data-qty-btn]").forEach(button=>button.addEventListener("click",this.manageQtyBtn.bind(this))),this.querySelectorAll("[data-qty-input]").forEach(button=>button.addEventListener("change",this.onQtyChange.bind(this))),this.giftWrappingAll(),this.expeditedShipping()}openCartDrawer(event){if(!window.globalVariables.cart_drawer){window.location.href=window.routes.cart_fetch_url||"/cart";return}document.querySelector("#mobile-menu-drawer").classList.contains("opened-drawer")&&document.querySelector(".close-mobile--navbar").dispatchEvent(new Event("click")),this.classList.add("opened-drawer"),siteOverlay.prototype.showOverlay(),Utility.forceFocus(this.querySelector(".cart-title"));let closeBtn=this.querySelector(".close-ajax--cart");Utility.trapFocus(this,closeBtn),event&&(event.preventDefault(),event.currentTarget.setAttribute("aria-expanded",!0))}closeCartDrawer(event,elementToFocus=!1){if(event!==void 0){event.preventDefault(),this.classList.remove("opened-drawer"),siteOverlay.prototype.hideOverlay(),event.currentTarget.setAttribute("aria-expanded",!1),Utility.removeTrapFocus(elementToFocus);let actionBtn=drawerSelectors.cartIconDesktop;window.innerWidth<1024&&(actionBtn=drawerSelectors.cartIconMobile),Utility.forceFocus(actionBtn)}}async _addExceedsLimitProperty(limit=4){let cart=window.globalVariables?.cart;
1(!this._cartSnapshotFresh||!Array.isArray(cart?.items))&&(cart=await fetch("/cart.js").then(response=>response.json()),window.globalVariables.cart=cart,this._cartSnapshotFresh=!0);const buckets={};cart.items.forEach(item=>{const group=item.properties&&item.properties._replacement_parts;group&&item.product_type==="Replacement Parts"&&(buckets[group]=(buckets[group]||0)+(item.quantity||1))});const desired=Object.values(buckets).some(count=>count>limit),current=(cart.attributes||{})._exceeds_limit,isSet=current===!0||current==="true",exists=current!=null&&current!=="";if(!(desired===isSet&&(desired||!exists))&&!this._exceedsInFlight){this._exceedsInFlight=!0;try{const response=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes:{_exceeds_limit:desired?"true":""}})});if(!response.ok)throw new Error(`cart/update.js ${response.status}`);window.globalVariables.cart=await response.json()}catch(e){console.warn("[exceedsLimit]",e)}finally{this._exceedsInFlight=!1}}}_validateOrphans(){const cart=window.globalVariables.cart;if(!cart||!cart.items)return;const attachedParentIds=cart.items.filter(item=>item.properties&&item.properties._attached_id&&!item.properties._attached_product).map(item=>String(item.properties._attached_id)),bundleParentIds=cart.items.filter(item=>item.properties&&item.properties._bundle_id&&!item.properties._bundled_product).map(item=>String(item.properties._bundle_id)),updates={};let hasOrphans=!1;cart.items.forEach(item=>{let reason=null;if(item.properties&&(item.properties._attached_product==="true"||item.properties._attached_product===!0)){const pid=item.properties._attached_id?String(item.properties._attached_id):null;(!pid||!attachedParentIds.includes(pid))&&(reason="Missing Attached Parent")}if(!reason&&item.properties&&(item.properties._bundled_product==="true"||item.properties._bundled_product===!0)){const pid=item.properties._bundle_id?String(item.properties._bundle_id):null;(!pid||!bundleParentIds.includes(pid))&&(reason="Missing Bundle Parent")}reason&&(updates[item.key]=0,hasOrphans=!0)}),hasOrphans&&fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates})}).then(response=>response.json()).then(()=>{this.getCartData("")}).catch(e=>console.error("Error removing orphans",e))}_updateCart(response,action){this.setAttribute("updating",!0);let cartHTML="";if(window.globalVariables.template!=="cart"?cartHTML=response["template-cart-drawer"]:cartHTML=response["template-cart"],!cartHTML)return;cartHTML=new DOMParser().parseFromString(cartHTML,"text/html");let cartJSONEle=cartHTML.querySelector("[data-cartScriptJSON]");this._cartSnapshotFresh=!!cartJSONEle,cartJSONEle&&(window.globalVariables.cart=JSON.parse(cartJSONEle.textContent));let cartElement=cartHTML.querySelector("ajax-cart form"),liveForm=this.querySelector("form");liveForm&&cartElement?liveForm.innerHTML=cartElement.innerHTML:console.warn("[updateCart] missing form or cartElement; skipped HTML swap");try{this.querySelector("[data-carttotal] span.money").innerHTML=Shopify.formatMoney(window.globalVariables.cart.total_price,window.globalVariables.money_format)}catch{}let elements=this.querySelectorAll("[data-checkoutBtns], [data-cartnote]");window.globalVariables.cart.item_count<=0?elements.forEach(div=>{div.classList.add("d-none")}):elements.forEach(div=>{div.classList.remove("d-none")}),this.setAttribute("updating",!1);let headerHTML=new DOMParser().parseFromString(response.header,"text/html"),cartIcon=headerHTML.getElementById("cart-icon-desktop"),cartCount=headerHTML.getElementsByClassName("cart-count");if(drawerSelectors.cartIconDesktop&&(drawerSelectors.cartIconDesktop.innerHTML=cartIcon.innerHTML),drawerSelectors.cartIconMobile&&(drawerSelectors.cartIconMobile.innerHTML=cartIcon.innerHTML),drawerSelectors.cartDrawerCount&&(drawerSelectors.cartDrawerCount.innerHTML=cartCount[0].innerHTML),window.subscriptions.enable_sub_limit&&window.globalVariables.templateSuffix==="subscription"){let cartDetails=window.globalVariables.cart,quantityCount=0;
1cartDetails.items.forEach(item=>{item.product_type=="Build a Box Subscription"&&(quantityCount=quantityCount+item.quantity)});let limitRange=window.subscriptions.product_limit;quantityCount<limitRange&&document.querySelectorAll(".subscription_limit_error_msg").forEach(msg=>{msg.classList.add("d-none")})}const giftWrappingElement=document.querySelector("ajax-cart .subscription-gift-wrapping"),expeditedShippingElement=document.querySelector("ajax-cart .subscription-expedited-shipping"),applyCartAddonVisibility=(showDiscreet,showExpedited)=>{if(giftWrappingElement)if(showDiscreet)giftWrappingElement.classList.add("d-flex"),giftWrappingElement.classList.remove("d-none");else{giftWrappingElement.classList.remove("d-flex"),giftWrappingElement.classList.add("d-none");const gwCheckbox=giftWrappingElement.querySelector('input[type="checkbox"]');gwCheckbox&&gwCheckbox.checked&&(gwCheckbox.checked=!1,gwCheckbox.dispatchEvent(new Event("change")))}if(expeditedShippingElement)if(showExpedited)expeditedShippingElement.classList.remove("d-none");else{expeditedShippingElement.classList.add("d-none");const esCheckbox=expeditedShippingElement.querySelector('input[type="checkbox"]');esCheckbox&&esCheckbox.checked&&(esCheckbox.checked=!1,esCheckbox.dispatchEvent(new Event("change")))}};if(window.AddonEligibility){const cartItems=window.globalVariables.cart.items;window.AddonEligibility.ready().then(()=>{applyCartAddonVisibility(window.AddonEligibility.shouldOffer(cartItems,"discreet"),window.AddonEligibility.shouldOffer(cartItems,"expedited"))})}typeof window.updateAddonPseudoVisibility=="function"&&window.updateAddonPseudoVisibility(),window.globalVariables.cart_drawer&&action==="open_drawer"&&window.globalVariables.template!=="cart"&&this.openCartDrawer(),action!==""&&Shopify.Cart.GiftWrap.processGiftWrappingForCartItem(0,!0,response).then(updatedResponse=>{updatedResponse&&this.getCartData("sync_update")})}getCartData(action){const fetchSection=window.globalVariables.template!=="cart"?"template-cart-drawer":"template-cart";return fetch(`${routes.cart_fetch_url}?sections=${fetchSection},header`,{cache:"no-store"}).then(response=>response.json()).then(response=>{try{this._updateCart(response,action)}catch(e){console.warn("[updateCart]",e)}}).then(()=>this._addExceedsLimitProperty()).then(()=>{this._validateOrphans()}).catch(e=>{console.warn("[getCartData]",e)})}updateItemQty(line,quantity,removing=!1,target=null){let lineItem=document.querySelectorAll("[data-cart-item]")[line-1],itemType=target?.dataset?.itemType?.includes("Subscription")||!1;if(removing&&itemType){let itemId=parseInt(target.dataset.itemId),updates={},attributes={},getWrapQty;if(updates[itemId]=0,itemType===!0){let giftWrappingId=parseInt(document.querySelector("input.gift-wrapping-id").value);Number.isNaN(giftWrappingId)||(getWrapQty=window.globalVariables.cart.items.find(item=>item.id===giftWrappingId)?.quantity||null,updates[giftWrappingId]=getWrapQty-1,getWrapQty-1===0&&(attributes["gift-wrapping"]="false"),getWrapQty===null&&(updates[giftWrappingId]=0,attributes["gift-wrapping"]="false"))}let expeditedId=parseInt(document.querySelector(".expedited-shipping-id")?.value);if(!Number.isNaN(expeditedId)){let getExpeditedQty=window.globalVariables.cart.items.find(item=>item.id===expeditedId)?.quantity||null;getExpeditedQty!==null&&(updates[expeditedId]=getExpeditedQty-1,getExpeditedQty-1<=0&&(attributes["items-with-expedited-shipping"]="",updates[expeditedId]=0))}lineItem&&lineItem.classList.add("updating");const body=JSON.stringify({updates,attributes});fetch(`${routes.cart_update_url}`,{...fetchConfig(),body}).then(response=>response.text()).then(state=>{this.getCartData()}).then(data=>{console.log("cart data")}).catch(error=>{console.log(error,"error")})}else{lineItem&&lineItem.classList.add("updating");const body=JSON.stringify({line,quantity});fetch(`${routes.cart_change_url}`,{...fetchConfig(),body}).then(response=>response.text()).then(state=>{let jsonObj=JSON.parse(state);this.getCartData(""),setTimeout(()=>{lineItem&&lineItem.classList.remove("updating")},1e3)}).catch(error=>{setTimeout(()=>{lineItem&&lineItem.classList.remove("updating")},1e3),console.log(error)})}}removeItem(event){const self=this;event.preventDefault();let currentTarget=event.currentTarget,itemIndex=currentTarget.dataset.index||null;itemIndex!=null&&self.updateItemQty(itemIndex,0,!0,currentTarget)}manageQtyBtn(event){event.preventDefault();let currentTarget=event.currentTarget,action=currentTarget.dataset.for||"increase",$qtyInput
1=currentTarget.closest("[data-qty-container]").querySelector("[data-qty-input]"),itemIndex=$qtyInput.dataset.index||1,currentQty=parseInt($qtyInput.value)||1,finalQty=1;if(action=="decrease"&&currentQty<=1)return!1;action=="decrease"?finalQty=currentQty-1:finalQty=currentQty+1,this.updateItemQty(itemIndex,finalQty)}onQtyChange(event){const $qtyInput=event.currentTarget,qtyValue=$qtyInput.value,itemIndex=$qtyInput.dataset.index||null;itemIndex&&this.updateItemQty(itemIndex,qtyValue)}cartNoteInput(){const cartNoteEle=document.querySelector('[data-cartNote] [name="note"]');if(!cartNoteEle)return;const cartNoteSave=document.querySelector("[data-saveNote]");cartNoteEle.addEventListener("input",event=>{cartNoteEle.value=cartNoteEle.value,cartNoteEle.dataset.default!=cartNoteEle.value?cartNoteSave.style.display="block":cartNoteSave.style.display="none"},!1),cartNoteEle.addEventListener("paste",event=>{cartNoteEle.value=cartNoteEle.value,cartNoteEle.dataset.default!=cartNoteEle.value?cartNoteSave.style.display="block":cartNoteSave.style.display="none"},!1),cartNoteSave.addEventListener("click",e=>{e.preventDefault();const cartNoteContainer=e.currentTarget.closest("[data-cartNote]");if(cartNoteContainer.querySelector('[name="note"]').value.trim().length<=0){alert("Add Note before proceeding");return}const submitBtn=cartNoteContainer.querySelector("[data-saveNote]"),waitText=submitBtn.dataset.adding_txt?submitBtn.dataset.adding_txt:"Saving...";submitBtn.innerHTML=waitText,submitBtn.disabled=!0,this.updateCartNote(cartNoteContainer)})}updateCartNote(cartNoteContainer){const _this=this,cartNoteEle=cartNoteContainer.querySelector('[name="note"]'),cartNote=cartNoteEle.value.trim(),resultEle=cartNoteContainer.querySelector("[data-resultMsg]"),submitBtn=cartNoteContainer.querySelector("[data-saveNote]"),defaultText=submitBtn.dataset.default?submitBtn.dataset.default:"Save";let body=JSON.stringify({note:cartNote});fetch(`${routes.cart_update_url}`,{...fetchConfig(),body}).then(function(data){data.status==200?(resultEle&&(resultEle.innerText="Added note to Order!",_this.manageResponseText(resultEle)),cartNoteEle&&(cartNoteEle.dataset.default=cartNote),submitBtn.style.display="none",submitBtn.innerHTML=defaultText,submitBtn.disabled=!1):(console.error("Request returned an error",data),resultEle&&(resultEle.innerText=data,_this.manageResponseText(resultEle)),submitBtn.innerHTML=defaultText,submitBtn.disabled=!1)}).catch(function(error){console.error("Request failed",error),resultEle&&(resultEle.innerText=error,_this.manageResponseText(resultEle)),submitBtn.innerHTML=defaultText,submitBtn.disabled=!1})}manageResponseText(element){Utility.fadeEffect(element,"fadeIn"),setTimeout(()=>{Utility.fadeEffect(element,"fadeOut")},3e3)}giftWrapping(){const self=this;[].slice.call(document.querySelectorAll(".subscription-gift-wrapping:not(.evented)")).map(gw=>{gw.classList.add("evented"),window.globalVariables.gw_ip_enabled==="true"&&window.country!=="United States of America"&&gw?.classList.add("d-none");const checkbox=gw.querySelector('input[type="checkbox"]');checkbox&&checkbox.addEventListener("change",()=>{const id=checkbox.id.replace("gift-wrapping-checkbox-","");id&&Shopify.Cart.GiftWrap.processGiftWrappingForCartItem(id,!0).then(()=>{self.getCartData("")})})})}giftWrappingAll(){const self=this;[].slice.call(document.querySelectorAll(".subscription-gift-wrapping:not(.evented)")).map(gw=>{gw.classList.add("evented"),window.globalVariables.gw_ip_enabled==="true"&&window.country!=="United States of America"&&gw?.classList.add("d-none");const checkbox=gw.querySelector('input[type="checkbox"]');checkbox&&checkbox.addEventListener("change",event=>{event.target.closest("[data-product-container]")||Shopify.Cart.GiftWrap.processGiftWrappingForCartItem(0,!0).then(()=>{self.getCartData("")})})})}expeditedShipping(){const self=this;[].slice.call(document.querySelectorAll(".subscription-expedited-shipping:not(.evented)")).map(es=>{es.classList.add("evented"),window.globalVariables.expedited_ip_enabled==="true"&&window.country!=="United States of America"&&es?.classList.add("d-none");const checkbox=es.querySelector('input[type="checkbox"]');checkbox&&checkbox.addEventListener("change",()=>{const id=checkbox.dataset.itemId;document.querySelectorAll(`input.expedited-shipping-checkbox[data-item-id="${id}"]`).forEach(cb=>{cb!==checkbox&&(cb.checked=checkbox.checked)}),Shopify.Cart.GiftWrap.processGiftWrappingForCartItem(id,!0).then(()=>{self.getCartData("")})})})}}customElements.define("ajax-cart",ajaxCart);
2//# sourceMappingURL=/cdn/shop/t/704/assets/component-ajax-cart.js.map?v=18147132924706714981790793055

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.