PageSourceSearch

https://drinktiiga.com/cdn/shop/t/79/assets/component-cart-items.js?v=161829787503768389431789445892

js drinktiiga.com collected 2026-10-05 02:05:50 UTC 20,311 bytes, 2 lines download raw bytes

1import{Component}from"@theme/component";import{fetchConfig,debounce,onAnimationEnd,prefersReducedMotion,resetShimmer,startViewTransition}from"@theme/utilities";import{morphSection,sectionRenderer}from"@theme/section-renderer";import{ThemeEvents,QuantitySelectorUpdateEvent}from"@theme/events";import{cartPerformance}from"@theme/performance";import{cartCount}from"@theme/cart-count";import{parsePlanTiers,pickPlan}from"@theme/selling-plans";import{enqueueCartMutation}from"@theme/cart-queue";import{createViewEventElement,CartErrorEvent,CartLinesUpdateEvent,StandardEvents}from"@shopify/events";export class CartItemsComponent extends createViewEventElement(Component){#debouncedOnChange=debounce(event=>{event instanceof QuantitySelectorUpdateEvent&&this.#onQuantityChange(event)},300);#pendingCartFetch=null;#optimisticFromEmpty=!1;#isExternalCartUpdate(event){return!(event.target instanceof Node)||!this.contains(event.target)}#handleDiscountUpdate=event=>{const external=this.#isExternalCartUpdate(event);event.promise?.then(({detail})=>{const sectionsHtml=detail?.sections?.[this.sectionId];sectionsHtml?(morphSection(this.sectionId,sectionsHtml,{mode:this.isDrawer?"hydration":"full"}),this.#updateCartQuantitySelectorButtonStates()):external&&sectionRenderer.renderSection(this.sectionId,{cache:!1,mode:this.isDrawer?"hydration":"full"})}).catch(error=>{error?.name!=="AbortError"&&console.warn("[cart-items] Event promise rejected:",error)})};#handleNoteUpdate=event=>{this.#isExternalCartUpdate(event)&&event.promise?.then(({detail})=>{const sectionsHtml=detail?.sections?.[this.sectionId];sectionsHtml?morphSection(this.sectionId,sectionsHtml,{mode:this.isDrawer?"hydration":"full"}):sectionRenderer.renderSection(this.sectionId,{cache:!1,mode:this.isDrawer?"hydration":"full"})}).catch(error=>{error?.name!=="AbortError"&&console.warn("[cart-items] Event promise rejected:",error)})};connectedCallback(){super.connectedCallback(),document.addEventListener(StandardEvents.cartLinesUpdate,this.#handleCartUpdate),document.addEventListener(ThemeEvents.quantitySelectorUpdate,this.#debouncedOnChange),document.addEventListener(StandardEvents.cartDiscountUpdate,this.#handleDiscountUpdate),document.addEventListener(StandardEvents.cartNoteUpdate,this.#handleNoteUpdate),this.isDrawer&&(cartCount.seed(this.#renderedDrawerCount()),cartCount.addEventListener(cartCount.changeEvent,this.#renderDrawerCount)),queueMicrotask(()=>this.reconcilePlans())}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(StandardEvents.cartLinesUpdate,this.#handleCartUpdate),document.removeEventListener(ThemeEvents.quantitySelectorUpdate,this.#debouncedOnChange),document.removeEventListener(StandardEvents.cartDiscountUpdate,this.#handleDiscountUpdate),document.removeEventListener(StandardEvents.cartNoteUpdate,this.#handleNoteUpdate),cartCount.removeEventListener(cartCount.changeEvent,this.#renderDrawerCount),this.#debouncedOnChange.cancel()}#onQuantityChange(event){if(!(event.target instanceof Node)||!this.contains(event.target))return;const{quantity,cartLine:line}=event.detail;if(!line)return;const lineItemRow=this.#rowForLine(line),offset=parseInt(lineItemRow?.dataset.quantityOffset??"",10)||0,lineQuantity=Math.max(0,quantity-offset);if(lineQuantity===0&&offset===0)return this.onLineItemRemove(line);const sellingPlan=lineItemRow&&lineQuantity>0?this.#planForQuantity(lineItemRow,quantity):null;if(this.updateQuantity({line,quantity:lineQuantity,action:"change",...sellingPlan&&lineItemRow?{sellingPlan,followUps:this.#groupFollowUps(lineItemRow,sellingPlan)}:{}}),!lineItemRow)return;lineItemRow.querySelector("text-component")?.shimmer()}#planForQuantity(row,quantity){const entries=parsePlanTiers(row.dataset.planTiers),ord=Number(row.dataset.planOrd),currentId=Number(row.dataset.planId);if(entries.length===0||!Number.isFinite(ord)||!currentId)return null;const ownGroup=(Number(row.dataset.lineQuantity)||0)+(Number(row.dataset.quantityOffset)||0),cadenceTotal=this.#subscriptionRows().filter(other=>Number(other.dataset.planOrd)===ord).reduce((sum,other)=>sum+(Number(other.dataset.lineQuantity)||0),0),target=pickPlan(entries,cadenceTotal-ownGroup+quantity,ord);return target&&target.id!==currentId?target.id:null}#groupFollowUps(row,sellingPlan){const groupKey=row.dataset.groupKey;return groupKey?(this.refs.cartItemRows??[]).filter(other=>other!==row&&other.dataset.groupKey===groupKey&&!other.classList.contains("removing")).map(other=>({key:other.dataset.key??"",quantity:Number(other.dataset.lineQuantity)||0,sellingPlan})).filter(followUp=>followUp.key&&followUp.quantity>0):[]}get#cartSectionIds(){const ids=new Set([this.sectionId]);for(const element of document.querySelectorAll("cart-items-component"))element instanceof HTMLElement&&element.dataset.sectionId&&ids.add(element.dataset.sectionId);return[...ids].join(",")}async#postCart(url,body){return(await fetch(url,fetchConfig("json",{body:JSON.stringify(body)}))).json()}#rowForLine(line){return(this.refs.cartItemRows??[]).find(row=>Number(row.dataset.line)===line)}#subscriptionRows(){return(this.refs.cartItemRows??[]).filter(row=>row.dataset.planOrd!==void 0&&!row.classList.contains("removing"))}reconcilePlans(){return enqueueCartMutation(()=>this.#reconcile())}async#reconcile(){const sections=this.#cartSectionIds;for(let pass=0;pass<2;pass++){const moves=this.#subscriptionRows().map(row=>({key:row.dataset.key??"",quantity:Number(row.dataset.lineQuantity)||0,sellingPlan:Number(row.dataset.planTarget)||0,current:Number(row.dataset.planId)||0}
1)).filter(move=>move.key&&move.quantity>0&&move.sellingPlan&&move.sellingPlan!==move.current);if(moves.length===0)return;this.#disableCartItems();let lastResponse=null;try{for(const[index,move]of moves.entries()){const body={id:move.key,quantity:move.quantity,selling_plan:move.sellingPlan},parsed=await this.#postCart(Theme.routes.cart_change_url,index===moves.length-1?{...body,sections,sections_url:window.location.pathname}:body);if(parsed.errors)break;lastResponse=parsed}}catch(error){console.warn("[cart-items] Plan reconcile failed:",error)}finally{this.#enableCartItems()}if(!lastResponse)return;await this.#renderCartSections(lastResponse.sections),this.#updateQuantitySelectors(lastResponse),this.#updateCartQuantitySelectorButtonStates(),this.#renderDrawerCount()}}async#renderCartSections(sections){for(const component of document.querySelectorAll("cart-items-component")){if(!(component instanceof CartItemsComponent))continue;const mode=component.isDrawer?"hydration":"full",html=sections?.[component.sectionId];html?await morphSection(component.sectionId,html,{mode}):await sectionRenderer.renderSection(component.sectionId,{cache:!1,mode})}}onLineItemRemove(line){const cartItemRowToRemove=this.#rowForLine(line),giftRows=cartItemRowToRemove?this.#orphanedGiftRows(cartItemRowToRemove):[],declined=cartItemRowToRemove?this.#declinedGiftsWith(cartItemRowToRemove):null;if(this.updateQuantity({line,quantity:0,action:"clear",clearKeys:giftRows.map(row=>row.dataset.key??"").filter(Boolean),...declined===null?{}:{attributes:{_declined_gifts:declined}}}),!cartItemRowToRemove)return;const rowsToRemove=[cartItemRowToRemove,...this.refs.cartItemRows.filter(row=>row.dataset.parentKey===cartItemRowToRemove.dataset.key),...giftRows];if(rowsToRemove.length==this.refs.cartItemRows.length&&document.getElementById("empty-cart-template")instanceof HTMLTemplateElement){startViewTransition(()=>{this.#revertToEmpty()},[this.isDrawer?"empty-cart-drawer":"empty-cart-page"]);return}rowsToRemove.forEach(row=>{const remove=()=>row.remove();if(prefersReducedMotion())return remove();row.style.setProperty("--row-height",`${row.clientHeight}px`),row.classList.add("removing"),onAnimationEnd(row,remove)})}#orphanedGiftRows(row){if(!row.classList.contains("cart-items__table-row--subscription"))return[];const rows=this.refs.cartItemRows??[];return rows.some(other=>other!==row&&other.classList.contains("cart-items__table-row--subscription")&&!other.classList.contains("removing"))?[]:rows.filter(other=>other.classList.contains("cart-items__table-row--gift")&&!other.classList.contains("removing"))}#declinedGiftsWith(row){if(!row.classList.contains("cart-items__table-row--gift"))return null;const variantId=row.dataset.variantId;if(!variantId)return null;const form=this.querySelector(".cart-form"),current=(form instanceof HTMLElement?form.dataset.declinedGifts??"":"").split(",").map(id=>id.trim()).filter(Boolean);return[...new Set([...current,variantId])].join(",")}onLineItemPlanChange(line,event){const select=event.target;if(!(select instanceof HTMLSelectElement))return;const sellingPlan=Number(select.value),quantity=parseInt(select.dataset.quantity??"",10)||1;if(!Number.isFinite(sellingPlan)||sellingPlan<=0)return;const row=this.#rowForLine(line);this.updateQuantity({line,quantity,sellingPlan,action:"change",followUps:row?this.#groupFollowUps(row,sellingPlan):[]})}onLineItemUpgrade(line,event){const row=this.#rowForLine(line),button=event.target instanceof HTMLElement?event.target:null;if(!row||!button)return;const quantity=Number(row.dataset.lineQuantity)||0,sellingPlan=Number(button.dataset.upgradePlan)||0;if(quantity<=0||!sellingPlan)return;this.updateQuantity({line,quantity,sellingPlan,action:"change",followUps:this.#groupFollowUps(row,sellingPlan)}),row.querySelector("text-component")?.shimmer()}updateQuantity(config){const cartPerformaceUpdateMarker=cartPerformance.createStartingMarker(`${config.action}:user-action`);this.#disableCartItems();const{line,quantity}=config,{cartTotal}=this.refs,sections=this.#cartSectionIds,lineId=this.#rowForLine(line)?.dataset.key??"",clearKeys=(config.clearKeys??[]).filter(key=>key&&key!==lineId),followUps=(config.followUps??[]).filter(followUp=>followUp.key&&followUp.key!==lineId),batchClear=clearKeys.length>
10&&lineId!=="",useUpdate=(batchClear||config.attributes!==void 0)&&lineId!=="",withSections=body=>({...body,sections,sections_url:window.location.pathname}),primaryBody=useUpdate?{updates:Object.fromEntries([[lineId,quantity],...clearKeys.map(key=>[key,0])]),...config.attributes?{attributes:config.attributes}:{}}:{line,quantity,...config.sellingPlan?{selling_plan:config.sellingPlan}:{}},url=useUpdate?Theme.routes.cart_update_url:Theme.routes.cart_change_url,cartErrors=parsed=>parsed.errors??(parsed.status?parsed.description||parsed.message:void 0);cartTotal?.shimmer();const deferredUpdatePromise=CartLinesUpdateEvent.createPromise();this.dispatchEvent(new CartLinesUpdateEvent({action:config.action==="change"&&quantity>0?"update":"remove",context:"cart",lines:[{id:lineId,quantity},...batchClear?clearKeys.map(key=>({id:key,quantity:0})):[]],promise:deferredUpdatePromise.promise})),(async()=>{let parsed=await this.#postCart(url,followUps.length?primaryBody:withSections(primaryBody));const errors=cartErrors(parsed);if(errors)return resetShimmer(this),this.#handleCartError(line,{...parsed,errors}),deferredUpdatePromise.reject(new Error(errors)),null;for(const[index,followUp]of followUps.entries()){const body={id:followUp.key,quantity:followUp.quantity,selling_plan:followUp.sellingPlan}
1,next=await this.#postCart(Theme.routes.cart_change_url,index===followUps.length-1?withSections(body):body);cartErrors(next)||(parsed=next)}return parsed})().then(async parsedResponseText=>{if(!parsedResponseText)return;resetShimmer(this);const sectionHtml=parsedResponseText.sections?.[this.sectionId];sectionHtml||(parsedResponseText=await this.fetchCartData());const newCartHiddenItemCount=sectionHtml?new DOMParser().parseFromString(sectionHtml,"text/html").querySelector('[ref="cartItemCount"]')?.textContent:String(parsedResponseText.item_count??""),newCartItemCount=newCartHiddenItemCount?parseInt(newCartHiddenItemCount,10):0;this.#updateQuantitySelectors(parsedResponseText),deferredUpdatePromise.resolve({cart:CartLinesUpdateEvent.createCartFromAjaxResponse(parsedResponseText),detail:{sections:parsedResponseText.sections,items:parsedResponseText.items,attributes:parsedResponseText.attributes,itemCount:newCartItemCount,source:"cart-items-component",didError:!1}}),sectionHtml?morphSection(this.sectionId,sectionHtml,{mode:this.isDrawer?"hydration":"full"}):await sectionRenderer.renderSection(this.sectionId,{cache:!1,mode:this.isDrawer?"hydration":"full"}),this.#renderDrawerCount(),this.#updateCartQuantitySelectorButtonStates(),this.reconcilePlans()}).catch(error=>{console.error(error),deferredUpdatePromise.reject(error),this.dispatchEvent(new CartErrorEvent({error:error?.message||"Failed to update cart",code:"SERVICE_UNAVAILABLE"}))}).finally(()=>{this.#enableCartItems(),cartPerformance.measureFromMarker(cartPerformaceUpdateMarker)})}#handleCartError=(line,parsedResponseText)=>{const quantityInput=this.#rowForLine(line)?.querySelector("input[data-cart-line]");if(!(quantityInput instanceof HTMLInputElement))throw new Error("Quantity input not found");quantityInput.value=quantityInput.defaultValue;const cartItemError=this.refs[`cartItemError-${line}`],cartItemErrorContainer=this.refs[`cartItemErrorContainer-${line}`];if(!(cartItemError instanceof HTMLElement))throw new Error("Cart item error not found");if(!(cartItemErrorContainer instanceof HTMLElement))throw new Error("Cart item error container not found");cartItemError.textContent=parsedResponseText.errors,cartItemErrorContainer.classList.remove("hidden"),this.dispatchEvent(new CartErrorEvent({error:parsedResponseText.errors||"Cart update failed",code:"INVALID"}))};#handleCartUpdate=event=>{if(event.target===this)return;const wasEmptyCartDrawer=this.isDrawer&&this.querySelector("[data-cart-drawer-empty]")!==null;event.action==="add"&&this.#optimisticAdd(event),event.promise?.then(async({detail})=>{if(this.removeAttribute("aria-busy"),detail?.didError){this.#revertOptimisticAdd(wasEmptyCartDrawer);return}this.#optimisticFromEmpty=!1;const cartItemsHtml=detail?.sections?.[this.sectionId],morphOptions={mode:this.isDrawer?"hydration":"full",injectStylesheet:wasEmptyCartDrawer};if(cartItemsHtml){const existingKeys=new Set(this.refs.cartItemRows?.map(row=>row.dataset.key)??[]);if(wasEmptyCartDrawer&&!this.querySelector("[data-optimistic]")?startViewTransition(()=>{morphSection(this.sectionId,cartItemsHtml,morphOptions),this.#renderDrawerCount()},["fill-cart-drawer"]):(await morphSection(this.sectionId,cartItemsHtml,morphOptions),this.#renderDrawerCount()),!wasEmptyCartDrawer&&!prefersReducedMotion())for(const row of this.refs.cartItemRows??[])existingKeys.has(row.dataset.key)||(row.classList.add("adding"),onAnimationEnd(row,()=>row.classList.remove("adding")));this.#updateCartQuantitySelectorButtonStates(),this.reconcilePlans()}else await sectionRenderer.renderSection(this.sectionId,{cache:!1,...morphOptions}),this.reconcilePlans()}).catch(error=>{this.#revertOptimisticAdd(wasEmptyCartDrawer),error?.name!=="AbortError"&&console.warn("[cart-items] Event promise rejected:",error)})};#optimisticAdd(event){if(!this.isDrawer)return;this.querySelector("[data-cart-drawer-empty]")!==null?(this.#swapToFilledShell(),this.#optimisticFromEmpty=!0,this.#previewShipping(event)):this.refs.cartTotal?.shimmer();const list=this.querySelector("[data-optimistic-list]")??this.querySelector('tbody[role="rowgroup"]')??this.querySelector("tbody"),itemTemplate=document.getElementById("optimistic-cart-item-template");if(!list||!(itemTemplate instanceof HTMLTemplateElement))return;this.setAttribute("aria-busy","true");const variantIds=new Set;for(const line of event.lines??[])(Number(line.quantity)||0)>0&&variantIds.add(String(line.merchandiseId??""));variantIds.size===0&&this.#optimisticFromEmpty&&variantIds.add("");for(const variantId of variantIds){if(variantId&&list.querySelector(`[data-optimistic-variant="${CSS.escape(variantId)}"]`))continue;const row=itemTemplate.content.firstElementChild?.cloneNode(!0);row instanceof HTMLTableRowElement&&(variantId&&(row.dataset.optimisticVariant=variantId),list.append(row))}}#previewShipping(event){const planInput=(event.target instanceof Element?event.target:null)?.querySelector('input[name="selling_plan"]'),hasSubscription=planInput instanceof HTMLInputElement&&planInput.value!=="",bar=this.querySelector("[data-optimistic-shipping]");
1if(!hasSubscription){bar instanceof HTMLElement&&bar.dataset.optimisticShipping==="threshold"&&bar.removeAttribute("hidden");return}bar?.removeAttribute("hidden");const fill=bar?.querySelector(".cart-shipping-bar__fill");fill instanceof HTMLElement&&(fill.style.width="100%");for(const pending of this.querySelectorAll("[data-optimistic-shipping-pending]"))pending.setAttribute("hidden","");for(const unlocked of this.querySelectorAll("[data-optimistic-shipping-unlocked]"))unlocked.removeAttribute("hidden")}#swapToFilledShell(){const inner=this.#drawerInner(),bodyTemplate=document.getElementById("optimistic-cart-body-template");bodyTemplate instanceof HTMLTemplateElement&&(inner?.classList.remove("cart-drawer--empty"),this.#replaceDrawerHeader("filled-cart-header-template"),this.replaceChildren(bodyTemplate.content.cloneNode(!0)),this.#renderDrawerCount(),this.closest("dialog")?.setAttribute("cart-summary-sticky","true"))}#revertToEmpty(){const bodyTemplate=document.getElementById("empty-cart-template");bodyTemplate instanceof HTMLTemplateElement&&(this.#drawerInner()?.classList.add("cart-drawer--empty"),this.#replaceDrawerHeader("empty-cart-header-template"),this.replaceChildren(bodyTemplate.content.cloneNode(!0)),this.#optimisticFromEmpty=!1,this.removeAttribute("aria-busy"))}#revertOptimisticAdd(wasEmpty){if(this.removeAttribute("aria-busy"),wasEmpty||this.#optimisticFromEmpty){this.#revertToEmpty();return}for(const row of this.querySelectorAll("[data-optimistic]"))row.remove()}#replaceDrawerHeader(templateId){const inner=this.#drawerInner(),template=document.getElementById(templateId);if(!inner||!(template instanceof HTMLTemplateElement))return;const current=inner.querySelector(":scope > .theme-drawer__header"),next=template.content.cloneNode(!0);current?current.replaceWith(next):inner.prepend(next)}#drawerInner(){return this.closest(".cart-drawer__inner")}#renderedDrawerCount(){const text=this.#drawerInner()?.querySelector(".cart-drawer__count")?.textContent??"";return parseInt(text.replace(/\D/g,""),10)||0}#renderDrawerCount=()=>{const inner=this.#drawerInner(),badge=inner?.querySelector(".cart-drawer__count");if(!(badge instanceof HTMLElement))return;const count=cartCount.value;badge.textContent=count>0?`(${count})`:"",badge.classList.toggle("visually-hidden",count===0);const label=inner?.querySelector("[data-cart-count-label]");label&&(label.textContent=count>0?`${Theme.translations.cart_count}: ${count}`:"")};#disableCartItems(){this.classList.add("cart-items-disabled")}#enableCartItems(){this.classList.remove("cart-items-disabled")}#updateQuantitySelectors(updatedCart){if(updatedCart.items)for(const item of updatedCart.items){const variantId=item.variant_id.toString(),selectors=document.querySelectorAll(`quantity-selector-component[data-variant-id="${variantId}"]`);for(const selector of selectors){const input=selector.querySelector("input[data-cart-quantity]");input&&(input.setAttribute("data-cart-quantity",item.quantity.toString()),"updateCartQuantity"in selector&&typeof selector.updateCartQuantity=="function"&&selector.updateCartQuantity())}}}#updateCartQuantitySelectorButtonStates(){for(const selector of document.querySelectorAll("cart-quantity-selector-component"))selector.updateButtonStates?.()}async fetchCartData(){return this.#pendingCartFetch?this.#pendingCartFetch:(this.#pendingCartFetch=(async()=>{const response=await fetch(`${Theme.routes.cart_url}.json`,{headers:{Accept:"application/json"},credentials:"same-origin"});if(!response.ok)throw new Error(`Failed to fetch cart: ${response.status} ${response.statusText}`);return await response.json()})().finally(()=>{this.#pendingCartFetch=null}),this.#pendingCartFetch)}get sectionId(){const{sectionId}=this.dataset;if(!sectionId)throw new Error("Section id missing");return sectionId}get isDrawer(){return this.dataset.drawer!==void 0}}customElements.get("cart-items-component")||customElements.define("cart-items-component",CartItemsComponent);
2//# sourceMappingURL=/cdn/shop/t/79/assets/component-cart-items.js.map?v=161829787503768389431789445892

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.