1import{CartErrorEvent,CartUpdateEvent,ThemeEvents}from"./events.js";import{cartPerformance}from"./performance-component.js";import{morphSection}from"./section-renderer.js";const selectors={cartChange:"[data-cart-change]",cartCount:"[data-cart-count]",cartCountLive:"[data-cart-count-live]",cartLabel:"[data-cart-label]",cartOpen:"[data-cart-drawer-open]",cartLine:"[data-cart-line-row]",cartSection:"[data-cart-drawer-section], [data-cart-page-section]"},routesRoot=window.Shopify?.routes?.root||"/",quantityUpdateTimers=new Map,freeGiftThrottle={limitPerWindow:6,windowMs:1e4,writes:[]};let freeGiftOperationInProgress=!1,freeGiftSyncQueued=!1,freeGiftSyncRequestedDuringOperation=!1,freeGiftThrottleReported=!1;function updateCartCount(count){count==null||Number.isNaN(Number(count))||(document.querySelectorAll(selectors.cartCount).forEach(node=>{node.textContent=String(count)}),document.querySelectorAll(selectors.cartCountLive).forEach(node=>{const label=node.closest(selectors.cartOpen)?.querySelector(selectors.cartLabel)?.textContent?.trim()||"Cart";node.textContent=`${label} - ${count}`}),document.querySelectorAll(selectors.cartOpen).forEach(node=>{const label=node.querySelector(selectors.cartLabel)?.textContent?.trim()||"Cart";node.setAttribute("aria-label",`${label} - ${count}`)}))}function cartSectionIds(){return Array.from(document.querySelectorAll(selectors.cartSection)).map(section=>section.dataset.sectionId).filter(Boolean).filter((sectionId,index,sectionIds)=>sectionIds.indexOf(sectionId)===index)}function cartSectionPayload(extra={}){const sectionIds=cartSectionIds();if(sectionIds.length===0)return extra;const sectionsUrl=new URL(window.location.href);return sectionsUrl.searchParams.delete("sections"),sectionsUrl.searchParams.delete("section_id"),{...extra,sections:sectionIds.join(","),sections_url:`${sectionsUrl.pathname}${sectionsUrl.search}`}}function sectionMode(sectionId){return document.querySelector(`[data-section-id="${CSS.escape(sectionId)}"]`)?.matches("[data-cart-drawer-section]")?"hydration":"full"}function itemCountFromRenderedSections(){const counts=Array.from(document.querySelectorAll("[data-cart-item-count]")).map(node=>Number(node.dataset.cartItemCount)).filter(count=>!Number.isNaN(count));return counts.length>0?counts[0]:void 0}function itemCountFromSectionHtml(sections={}){for(const html of Object.values(sections||{})){if(typeof html!="string")continue;const node=new DOMParser().parseFromString(html,"text/html").querySelector("[data-cart-item-count]");if(!node)continue;const count=Number(node.dataset.cartItemCount);if(!Number.isNaN(count))return count}}function applyCartSections(sections={}){const renderedCount=itemCountFromSectionHtml(sections);Object.entries(sections||{}).forEach(([sectionId,html])=>{morphSection(sectionId,html,sectionMode(sectionId))}),updateCartCount(renderedCount??itemCountFromRenderedSections())}async function renderKnownCartSections(){await Promise.all(cartSectionIds().map(sectionId=>window.MedistikSectionRenderer?.sectionRenderer.renderSection(sectionId,{mode:sectionMode(sectionId),cache:!1}))),updateCartCount(itemCountFromRenderedSections())}function cartErrorSurface(button){return button.closest(selectors.cartSection)}function currentCartErrorSurface(fallback=null){return fallback?.isConnected?fallback:document.querySelector(selectors.cartSection)}function setCartChangeError(surface,message){if(!surface)return;let error=surface.querySelector("[data-cart-change-error]");if(!message){error?.remove();return}error||(error=document.createElement("p"),error.className="md-form-error",error.setAttribute("role","alert"),error.dataset.cartChangeError="",(surface.querySelector("[data-cart-drawer-items]")||surface.querySelector(".md-cart__inner")||surface).prepend(error)),error.textContent=message}function setCartChangeBusy(node,busy){node&&(node.toggleAttribute("aria-busy",busy),"disabled"in node&&(node.disabled=busy))}function setLineRemoving(node,removing){const line=node?.closest(selectors.cartLine);line&&(line.toggleAttribute("data-cart-line-removing",removing),line.toggleAttribute("aria-busy",removing))}async function cartChangeErrorFromResponse(response){const contentType=response.headers.get("content-type")||"",cartError=new Error("Unable to update cart.");if(cartError.cartStatus=response.status,contentType.includes("application/json")){try{const error=await response.json();cartError.message=error.description||error.message||cartError.message,cartError.errors=error.errors||null}catch{}return cartError}if(contentType.includes("text/html")){const body=await response.text().catch(()=>"");(/verifying your connection/i.test(body)||response.status===401||response.status===403)&&(cartError.message="Unable to update cart. Storefront verification blocked the cart request.")}return cartError}function freeGiftState(){const stateNode=document.querySelector("[data-free-gift-state]"),cartDrawer=document.querySelector("[data-cart-drawer-section]");return!stateNode||!cartDrawer?null:{cartDrawer,enabled:stateNode.dataset.freeGiftEnabled==="true",threshold:Number(stateNode.dataset.freeGiftThreshold||0),variantId:stateNode.dataset.freeGiftVariantId||"",giftLineKey:stateNode.dataset.freeGiftLineKey||"",giftLineVariantId:stateNode.dataset.freeGiftLineVariantId||"",giftLineQuantity:Number(stateNode.dataset.freeGiftLineQuantity||0),extraGiftLineKeys:(stateNode.dataset.freeGiftExtraKeys||"").split(",").filter(
1Boolean),qualifyingTotal:Number(stateNode.dataset.cartQualifyingTotal||0)}}function freeGiftWriteAllowed(){const now=Date.now(),{writes,windowMs,limitPerWindow}=freeGiftThrottle;for(;writes.length>0&&now-writes[0]>windowMs;)writes.shift();return writes.length>=limitPerWindow?(freeGiftThrottleReported||(freeGiftThrottleReported=!0,console.warn("Free gift sync paused: too many cart writes in a row.")),!1):(writes.push(now),!0)}function setFreeGiftSyncing(syncing){document.documentElement.toggleAttribute("data-free-gift-syncing",syncing)}async function syncFreeGift(){if(freeGiftOperationInProgress){freeGiftSyncRequestedDuringOperation=!0;return}const state=freeGiftState();if(!state||!state.enabled||!state.variantId||state.variantId==="0")return;const qualifies=state.qualifyingTotal>=state.threshold,giftProductChanged=state.giftLineKey&&state.giftLineVariantId&&state.giftLineVariantId!==state.variantId,duplicateGiftLineKey=state.extraGiftLineKeys[0],shouldRemove=!!state.giftLineKey&&(!qualifies||giftProductChanged),shouldAdd=qualifies&&!state.giftLineKey,shouldNormalizeQuantity=qualifies&&!!state.giftLineKey&&!giftProductChanged&&state.giftLineQuantity!==1;if(!duplicateGiftLineKey&&!shouldRemove&&!shouldAdd&&!shouldNormalizeQuantity||!freeGiftWriteAllowed())return;const endpoint=shouldAdd&&!duplicateGiftLineKey?"cart/add.js":"cart/change.js";let payload;duplicateGiftLineKey?payload=cartSectionPayload({id:duplicateGiftLineKey,quantity:0}):shouldAdd?payload=cartSectionPayload({items:[{id:state.variantId,quantity:1,properties:{_free_gift:"true"}}]}):payload=cartSectionPayload({id:state.giftLineKey,quantity:shouldRemove?0:1}),freeGiftOperationInProgress=!0,setFreeGiftSyncing(!0),setCartChangeError(state.cartDrawer,"");try{const response=await fetch(`${routesRoot}${endpoint}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(payload)});if(!response.ok)throw await cartChangeErrorFromResponse(response);const result=await response.json();document.dispatchEvent(new CartUpdateEvent(result,"cart-free-gift",{source:"cart-free-gift",sections:result.sections||{},itemCount:result.item_count}))}catch(error){const message=error.message||"Unable to update cart.";setCartChangeError(currentCartErrorSurface(state.cartDrawer),message),document.dispatchEvent(new CartErrorEvent("cart-free-gift",message,error.description,error.errors))}finally{freeGiftOperationInProgress=!1,setFreeGiftSyncing(!1),freeGiftSyncRequestedDuringOperation&&(freeGiftSyncRequestedDuringOperation=!1,queueFreeGiftSync())}}function queueFreeGiftSync(){freeGiftSyncQueued||(freeGiftSyncQueued=!0,queueMicrotask(()=>{freeGiftSyncQueued=!1,syncFreeGift()}))}function mutationChangesFreeGiftState(mutation){return mutation.type==="attributes"?mutation.target instanceof Element&&mutation.target.matches("[data-free-gift-state]"):[...mutation.addedNodes,...mutation.removedNodes].some(node=>node instanceof Element&&(node.matches("[data-free-gift-state]")||!!node.querySelector("[data-free-gift-state]")))}function observeFreeGiftState(){const cartDrawer=document.querySelector("[data-cart-drawer-section]");if(!cartDrawer||typeof MutationObserver>"u")return;new MutationObserver(mutations=>{mutations.some(mutationChangesFreeGiftState)&&queueFreeGiftSync()}).observe(cartDrawer,{attributes:!0,attributeFilter:["data-cart-qualifying-total","data-free-gift-enabled","data-free-gift-threshold","data-free-gift-variant-id","data-free-gift-line-key","data-free-gift-line-variant-id","data-free-gift-line-quantity","data-free-gift-extra-keys"],childList:!0,subtree:!0})}function sourceIdFor(node){return node.id||node.closest("[id]")?.id||"cart-items"}async function changeCartLine(trigger,lineKey,quantity){if(!lineKey||Number.isNaN(quantity)||trigger?.getAttribute("aria-busy")==="true")return;const sourceId=sourceIdFor(trigger),errorSurface=cartErrorSurface(trigger);setCartChangeError(errorSurface,""),setCartChangeBusy(trigger,!0),quantity===0&&setLineRemoving(trigger,!0);const requestMarker=cartPerformance.createStartingMarker("change:request"),payload=cartSectionPayload({id:lineKey,quantity});try{const response=await fetch(`${routesRoot}cart/change.js`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(payload)});if(!response.ok)throw await cartChangeErrorFromResponse(response);const result=await response.json();cartPerformance.measureFromMarker(requestMarker),document.dispatchEvent(new CartUpdateEvent(result,sourceId,{source:"cart-change",sections:result.sections||{},itemCount:result.item_count,line:lineKey,quantity}))}catch(error){const message=error.message||"Unable to update cart.";await renderKnownCartSections().catch(()=>{}),setCartChangeError(currentCartErrorSurface(errorSurface),message),document.dispatchEvent(new CartErrorEvent(sourceId,message,error.description,error.errors))}finally{setCartChangeBusy(trigger,!1),setLineRemoving(trigger,!1)}}function queueQuantityChange(trigger,line,quantity){const key=`${line}`;quantity===0&&setLineRemoving(trigger,!0),window.clearTimeout(quantityUpdateTimers.get(key)),quantityUpdateTimers.set(key,window.setTimeout(()=>{quantityUpdateTimers.delete(key),changeCartLine(trigger,line,quantity)},300))}function handleCartEvent(event){const sections=event.detail?.data?.sections,itemCount=event.detail?.data?.itemCount??event.detail?.resource?.item_count;sections&&Object.keys(sections).length>0?applyCartSections(sections):renderKnownCartSections().catch(()=>{}),updateCartCount(itemCount),queueFreeGiftSync()}document.addEventListener(ThemeEvents.cartUpdate,handleCartEvent),document.addEventListener(ThemeEvents.discountUpdate,handleCartEvent),document.addEventListener(ThemeEvents.quantitySelectorUpdate,event=>{const{cartLine,quantity}=event.detail||{};if(!cartLine)return;cartPerformance.measureFromEvent("change:user-action",event);const trigger=event.target instanceof Element?event.target:document.getElementById(event.detail.sourceId)||document.activeElement;queueQuantityChange(trigger,cartLine,Number(quantity))}),document.addEventListener("click",event=>{if(!(event.target instanceof Element))return;const changeButton=event.target.closest(selectors.cartChange);
1if(changeButton){event.preventDefault();const line=changeButton.dataset.line,quantity=Number(changeButton.dataset.quantity);queueQuantityChange(changeButton,line,quantity);return}}),queueFreeGiftSync(),observeFreeGiftState(),window.MedistikCartItems={changeLine:changeCartLine,updateCartCount,applyCartSections}; 2//# sourceMappingURL=/cdn/shop/t/145/assets/cart-items-component.js.map?v=39920193030222204041785169577
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.