PageSourceSearch

https://saltycaptain.com.au/cdn/shop/t/212/assets/cart.js?v=139707659002880097591790801601

js saltycaptain.com.au collected 2026-10-04 02:54:44 UTC 18,207 bytes, 2 lines download raw bytes

1"use strict";class CartUI{constructor(){this.isRefreshing=!1,this.sectionRefreshQueued=!1,this.lineRequests=new Set,this.lastFocusedTrigger=null,this.handleClick=this.handleClick.bind(this),this.handleChange=this.handleChange.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.handleCartRefresh=this.handleCartRefresh.bind(this),this.init()}init(){document.addEventListener("click",this.handleClick),document.addEventListener("change",this.handleChange),document.addEventListener("keydown",this.handleKeydown),document.addEventListener("cart:refresh",this.handleCartRefresh)}get drawer(){return document.querySelector("[data-cart-drawer-root]")}get cartPage(){return document.querySelector("[data-main-cart-root]")}get cartCountElements(){return document.querySelectorAll("[data-cart-count]")}get cartUrl(){return window.__glowRoutes?.cartUrl||window.Shopify?.routes?.cart_url||"/cart"}get sectionsUrlForBundled(){const url=this.cartUrl;return url.startsWith("/")?url:`/${url}`}buildBundledSectionsPayload(){const targets=this.getSectionTargets();return targets.length?{sections:targets.map(t=>t.id).join(","),sections_url:this.sectionsUrlForBundled}:null}applyBundledSections(sections){sections&&this.getSectionTargets().forEach(target=>{const html=sections[target.id];html&&this.replaceSection(target.selector,html)})}getSectionTargets(){const targets=[];return this.drawer&&targets.push({id:this.drawer.dataset.sectionId||"cart-drawer",selector:"[data-cart-drawer-root]"}),this.cartPage&&targets.push({id:this.cartPage.dataset.sectionId||"cart",selector:"[data-main-cart-root]"}),targets.filter((target,index,array)=>array.findIndex(item=>item.id===target.id)===index)}isDrawerOpen(){return!!this.drawer?.classList.contains("is-active")}openDrawer(trigger=null){const drawer=this.drawer;if(!drawer)return;trigger&&(this.lastFocusedTrigger=trigger),drawer.classList.add("is-active"),drawer.setAttribute("aria-hidden","false"),document.body.classList.add("cart-drawer-open");const closeButton=drawer.querySelector("[data-cart-drawer-close]");closeButton&&requestAnimationFrame(()=>closeButton.focus()),updateCartShippingEstimate(),initCartExpressButtons()}closeDrawer(){const drawer=this.drawer;drawer&&(this.isRefreshing&&(this._userClosedDuringRefresh=!0),drawer.classList.remove("is-active"),drawer.setAttribute("aria-hidden","true"),document.body.classList.remove("cart-drawer-open"),this.lastFocusedTrigger&&(this.lastFocusedTrigger.focus(),this.lastFocusedTrigger=null))}handleKeydown(event){event.key==="Escape"&&this.isDrawerOpen()&&this.closeDrawer()}async handleClick(event){const openButton=event.target.closest("[data-cart-open], [data-cart-toggle]");if(openButton){event.preventDefault(),this.openDrawer(openButton);return}if(event.target.closest("[data-cart-drawer-close]")){event.preventDefault(),this.closeDrawer();return}if(event.target.closest("[data-cart-drawer-overlay]")){event.preventDefault(),this.closeDrawer();return}const removeButton=event.target.closest("[data-cart-remove]");if(removeButton){event.preventDefault();const cartItem=removeButton.closest("[data-cart-item]"),lineKey=cartItem?.dataset.lineKey;if(!lineKey)return;await this.updateLineItem(lineKey,0,cartItem);return}const minusButton=event.target.closest("[data-cart-quantity-minus]");if(minusButton){event.preventDefault();const cartItem=minusButton.closest("[data-cart-item]"),quantityInput=cartItem?.querySelector("[data-cart-quantity-input]"),lineKey=cartItem?.dataset.lineKey;if(!cartItem||!quantityInput||!lineKey)return;const currentValue=parseInt(quantityInput.value,10)||1,nextValue=Math.max(1,currentValue-1);if(nextValue===currentValue)return;quantityInput.value=nextValue,await this.updateLineItem(lineKey,nextValue,cartItem);return}const plusButton=event.target.closest("[data-cart-quantity-plus]");if(plusButton){event.preventDefault();const cartItem=plusButton.closest("[data-cart-item]"),quantityInput=cartItem?.querySelector("[data-cart-quantity-input]"),lineKey=cartItem?.dataset.lineKey;if(!cartItem||!quantityInput||!lineKey)return;const nextValue=(parseInt(quantityInput.value,10)||1)+1;quantityInput.value=nextValue,await this.updateLineItem(lineKey,nextValue,cartItem)}}async handleChange(event){const quantityInput=event.target.closest("[data-cart-quantity-input]");if(!quantityInput)return;const cartItem=quantityInput.closest("[data-cart-item]"),lineKey=cartItem?.dataset.lineKey;if(!cartItem||!lineKey)return;let nextValue=parseInt(quantityInput.value,10)||1;nextValue=Math.max(1,nextValue);const previousValue=parseInt(quantityInput.defaultValue,10)||1;quantityInput.value=nextValue,nextValue!==previousValue&&await this.updateLineItem(lineKey,nextValue,cartItem)}async handleCartRefresh(event){const shouldOpenDrawer=!!event.detail?.openDrawer,wasOpenBefore=this.isDrawerOpen();this._userClosedDuringRefresh=!1,await this.renderSections(),!this._userClosedDuringRefresh&&(shouldOpenDrawer&&!this.isDrawerOpen()?this.openDrawer():wasOpenBefore&&!this.isDrawerOpen()&&this.openDrawer())}async updateLineItem(lineKey,quantity,cartItem=null){if(!this.lineRequests.has(lineKey)){this.lineRequests.add(lineKey);try{cartItem&&cartItem.classList.add("is-loading");const drawerWasOpen=this.isDrawerOpen(),cart=await this.changeLineItem(lineKey,quantity);cart&&typeof cart.item_count<"u"&&this.updateCartCount(cart.item_count),this.dispatchRefresh({openDrawer:drawerWasOpen})}catch(error){console.error("Cart line item update error:",error)}finally{cartItem&&cartItem.classList.remove("is-loading"),this.lineRequests.delete(lineKey)}}}
1async renderSections(){if(this.isRefreshing){this.sectionRefreshQueued=!0;return}this.isRefreshing=!0;try{const targets=this.getSectionTargets();if(!targets.length){this.isRefreshing=!1;return}const query=targets.map(target=>target.id).map(id=>encodeURIComponent(id)).join(","),cacheBust=`_=${Date.now()}`,url=`${this.cartUrl}?sections=${query}&${cacheBust}`,response=await fetch(url,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!response.ok)throw new Error("Failed to render cart sections");const sections=await response.json();targets.forEach(target=>{sections[target.id]&&this.replaceSection(target.selector,sections[target.id])}),await this.syncCartCountFromApi()}catch(error){console.error("Cart sections refresh error:",error)}finally{this.isRefreshing=!1,this.sectionRefreshQueued&&(this.sectionRefreshQueued=!1,await this.renderSections())}}replaceSection(selector,html){const currentElement=document.querySelector(selector);if(!currentElement||!html)return;const preserveDrawerOpen=selector==="[data-cart-drawer-root]"&&currentElement.classList.contains("is-active"),oldSwiper=currentElement.querySelector("[data-cart-recommendations-swiper]");oldSwiper&&oldSwiper.swiper&&oldSwiper.swiper.destroy(!0,!0);const oldEmpty=currentElement.querySelector("[data-cart-empty-swiper]");oldEmpty&&oldEmpty.swiper&&oldEmpty.swiper.destroy(!0,!0);const nextElement=new DOMParser().parseFromString(html,"text/html").querySelector(selector);if(nextElement){preserveDrawerOpen&&(nextElement.classList.add("is-active"),nextElement.setAttribute("aria-hidden","false")),currentElement.replaceWith(nextElement),preserveDrawerOpen&&document.body.classList.add("cart-drawer-open"),initCartRecommendationsSwiper(),updateCartShippingEstimate(),initCartExpressButtons();return}if(currentElement.outerHTML=html,preserveDrawerOpen){const nextRoot=document.querySelector(selector);nextRoot&&(nextRoot.classList.add("is-active"),nextRoot.setAttribute("aria-hidden","false"),document.body.classList.add("cart-drawer-open"))}initCartRecommendationsSwiper(),updateCartShippingEstimate(),initCartExpressButtons()}updateCartCount(count){this.cartCountElements.forEach(element=>{element.textContent=count,count>0?element.classList.remove("is-hidden"):element.classList.add("is-hidden")}),count===0&&sessionStorage.removeItem("cart_upsell_upgraded")}async syncCartCountFromApi(){try{const cart=await this.getCartData();this.updateCartCount(cart.item_count||0)}catch(error){console.error("Cart count sync error:",error)}}dispatchRefresh(detail={}){if(typeof window.refreshCartUi=="function"){window.refreshCartUi(detail);return}document.dispatchEvent(new CustomEvent("cart:refresh",{detail}))}async getCartData(){if(typeof window.getCartData=="function")return await window.getCartData();const response=await fetch("/cart.js",{method:"GET",headers:{Accept:"application/json"}});if(!response.ok)throw new Error("Failed to load cart");return response.json()}async changeLineItem(lineKey,quantity){if(typeof window.updateCartItemQuantity=="function")return await window.updateCartItemQuantity(lineKey,quantity);const bundled=this.buildBundledSectionsPayload(),body={id:lineKey,quantity,...bundled||{}},response=await fetch("/cart/change.js",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(body)});if(!response.ok)throw new Error("Failed to update cart item quantity");const cart=await response.json();return cart.sections&&this.applyBundledSections(cart.sections),cart}}document.addEventListener("DOMContentLoaded",()=>{window.cartUi=new CartUI,initCartRecommendationsSwiper(),updateCartShippingEstimate(),initCartExpressButtons()}),document.addEventListener("cart:refresh",()=>{initCartRecommendationsSwiper(),updateCartShippingEstimate(),initCartExpressButtons()});function initCartUpsell(){}function initCartExpressButtons(){window.Shopify&&(Shopify.StorefrontExpressButtons&&typeof Shopify.StorefrontExpressButtons.initialize=="function"&&Shopify.StorefrontExpressButtons.initialize(),Shopify.PaymentButton&&typeof Shopify.PaymentButton.init=="function"&&Shopify.PaymentButton.init())}function formatCartMoney(cents,moneyFormat){const value=Number(cents)||0;if(window.Shopify&&typeof window.Shopify.formatMoney=="function"&&moneyFormat)return window.Shopify.formatMoney(value,moneyFormat).replace(/<\/?[^>]+(>|$)/g,"");const currency=window.Shopify?.currency?.active||"AUD";return new Intl.NumberFormat(void 0,{style:"currency",currency}).format(value/100)}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms))}async function fetchShopifyShippingRates(summary,retries=4){const country=(summary.dataset.shippingCountry||"AU").trim(),province=(summary.dataset.shippingProvince||"").trim(),zip=(summary.dataset.shippingZip||"").trim();if(!country)return[];const params=new URLSearchParams;params.set("shipping_address[country]",country),province&&params.set("shipping_address[province]",province),zip&&params.set("shipping_address[zip]",zip);const response=await fetch(`/cart/shipping_rates.json?${params.toString()}`,{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!response.ok)throw new Error("Shipping rates request failed");const data=await response.json(),rates=Array.isArray(data.shipping_rates)?data.shipping_rates:[];return!rates.length&&retries>0?(await sleep(400),fetchShopifyShippingRates(summary,retries-1)):rates}function pickCheapestShippingRate(rates){return rates.length?rates.reduce((cheapest,rate)=>
1{const price=Math.round(parseFloat(rate.price)*100)||0,cheapestPrice=Math.round(parseFloat(cheapest.price)*100)||0;return price<cheapestPrice?rate:cheapest}):null}async function updateCartShippingEstimate(){const summary=document.querySelector("[data-cart-summary]");if(!summary)return;const shippingEl=summary.querySelector("[data-cart-shipping-value]"),grandTotalEl=summary.querySelector("[data-cart-grand-total]"),checkoutEl=summary.querySelector("[data-cart-checkout-total]");if(!shippingEl||!grandTotalEl||!checkoutEl)return;const cartTotal=Number(summary.dataset.cartTotal)||0,threshold=Number(summary.dataset.freeShippingThreshold)||0,moneyFormat=summary.dataset.moneyFormat||"",applyShipping=shippingCents=>{const safeShipping=Math.max(0,Number(shippingCents)||0),grandTotal=cartTotal+safeShipping;safeShipping===0?(shippingEl.textContent="FREE",shippingEl.classList.add("cart-summary__value--free")):(shippingEl.textContent=formatCartMoney(safeShipping,moneyFormat),shippingEl.classList.remove("cart-summary__value--free")),grandTotalEl.textContent=formatCartMoney(grandTotal,moneyFormat),checkoutEl.textContent=`Checkout ${formatCartMoney(grandTotal,moneyFormat)}`};shippingEl.textContent="Calculating\u2026",shippingEl.classList.remove("cart-summary__value--free");try{const rates=await fetchShopifyShippingRates(summary),cheapest=pickCheapestShippingRate(rates);if(!cheapest){if(threshold>0&&cartTotal>=threshold){applyShipping(0);return}shippingEl.textContent="At checkout",shippingEl.classList.remove("cart-summary__value--free"),grandTotalEl.textContent=formatCartMoney(cartTotal,moneyFormat),checkoutEl.textContent=`Checkout ${formatCartMoney(cartTotal,moneyFormat)}`;return}const shippingCents=Math.round(parseFloat(cheapest.price)*100)||0;applyShipping(shippingCents)}catch(error){if(console.error("Cart shipping estimate error:",error),threshold>0&&cartTotal>=threshold){applyShipping(0);return}shippingEl.textContent="At checkout",shippingEl.classList.remove("cart-summary__value--free"),grandTotalEl.textContent=formatCartMoney(cartTotal,moneyFormat),checkoutEl.textContent=`Checkout ${formatCartMoney(cartTotal,moneyFormat)}`}}window.updateCartShippingEstimate=updateCartShippingEstimate;async function getShopifyShippingCents(options){const opts=options||{},country=String(opts.country||"AU").trim(),province=String(opts.province||"").trim(),zip=String(opts.zip||"").trim();if(!country)return null;const params=new URLSearchParams;params.set("shipping_address[country]",country),province&&params.set("shipping_address[province]",province),zip&&params.set("shipping_address[zip]",zip);let rates=[];for(let attempt=0;attempt<5;attempt+=1){const response=await fetch(`/cart/shipping_rates.json?${params.toString()}`,{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!response.ok)throw new Error("Shipping rates request failed");const data=await response.json();if(rates=Array.isArray(data.shipping_rates)?data.shipping_rates:[],rates.length)break;await sleep(400)}const cheapest=pickCheapestShippingRate(rates);return cheapest?Math.round(parseFloat(cheapest.price)*100)||0:null}window.getShopifyShippingCents=getShopifyShippingCents;async function fetchCart(){const res=await fetch("/cart.js",{headers:{Accept:"application/json"}});if(!res.ok)throw new Error("Failed to fetch cart");return res.json()}async function changeCartItem(key,quantity){const res=await fetch("/cart/change.js",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:key,quantity})});if(!res.ok)throw new Error("Failed to change cart item");return res.json()}async function addToCart(variantId,quantity){const res=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:Number(variantId),quantity})});if(!res.ok)throw new Error("Failed to add to cart");return res.json()}async function addToCartWithPlan(variantId,quantity,sellingPlan){const res=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({id:Number(variantId),quantity,selling_plan:Number(sellingPlan)})});if(!res.ok)throw new Error("Failed to add to cart with plan");return res.json()}
1function initCartRecommendationsSwiper(){if(typeof Swiper>"u")return;const el=document.querySelector("[data-cart-recommendations-swiper]");el&&!el.swiper&&new Swiper(el,{slidesPerView:2,spaceBetween:10,watchOverflow:!0,navigation:{prevEl:"[data-cart-rec-prev]",nextEl:"[data-cart-rec-next]"}});const emptyEl=document.querySelector("[data-cart-empty-swiper]");emptyEl&&!emptyEl.swiper&&new Swiper(emptyEl,{slidesPerView:2,spaceBetween:10,watchOverflow:!0,navigation:{prevEl:"[data-cart-empty-prev]",nextEl:"[data-cart-empty-next]"}})}document.addEventListener("click",async event=>{const btn=event.target.closest("[data-cart-rec-add]");if(!btn)return;const variantId=Number(btn.dataset.variantId);if(variantId){btn.disabled=!0;try{await addToCart(variantId,1),window.cartUi&&window.cartUi.dispatchRefresh({openDrawer:!0})}catch(error){console.error("Cart recommendation add error:",error)}finally{btn.disabled=!1}}}),document.addEventListener("click",async event=>{const btn=event.target.closest("[data-cart-upsell-switch]");if(!btn)return;const upsellBlock=btn.closest("[data-cart-upsell]");if(!upsellBlock)return;const upgradeVariantId=Number(upsellBlock.dataset.upgradeVariantId),currentLineKey=upsellBlock.dataset.currentLineKey,sellingPlan=upsellBlock.dataset.sellingPlan||"";if(!upgradeVariantId||!currentLineKey)return;const initialText=btn.textContent;btn.disabled=!0,btn.textContent="Switching...";try{await changeCartItem(currentLineKey,0),sellingPlan?await addToCartWithPlan(upgradeVariantId,1,sellingPlan):await addToCart(upgradeVariantId,1),await forceRefreshCartDrawer()}catch(error){console.error("Cart upsell switch error:",error),btn.disabled=!1,btn.textContent=initialText}});async function forceRefreshCartDrawer(){const drawer=document.querySelector("[data-cart-drawer-root]");if(!drawer)return;const sectionId=drawer.dataset.sectionId||"cart-drawer",url=`/?sections=${encodeURIComponent(sectionId)}&_=${Date.now()}`;try{const response=await fetch(url,{method:"GET",headers:{Accept:"application/json"}});if(!response.ok)throw new Error("Section fetch failed");const html=(await response.json())[sectionId];if(!html)throw new Error("No section HTML");const nextDrawer=new DOMParser().parseFromString(html,"text/html").querySelector("[data-cart-drawer-root]");if(!nextDrawer)throw new Error("Drawer not found in parsed HTML");nextDrawer.classList.add("is-active"),nextDrawer.setAttribute("aria-hidden","false"),drawer.replaceWith(nextDrawer),document.body.classList.add("cart-drawer-open");const cart=await fetchCart();window.cartUi&&window.cartUi.updateCartCount(cart.item_count||0),initCartRecommendationsSwiper(),updateCartShippingEstimate(),initCartExpressButtons()}catch(err){console.error("forceRefreshCartDrawer:",err),window.location.reload()}}
2//# sourceMappingURL=/cdn/shop/t/212/assets/cart.js.map?v=139707659002880097591790801601

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.