PageSourceSearch

https://badesofa.com/cdn/shop/t/120/assets/gamification.js?v=90429056084692690441784219852

js badesofa.com collected 2026-10-04 06:54:06 UTC 17,239 bytes, 2 lines download raw bytes

1import{fetchCart}from"theme";(function(){"use strict";let gamificationGiftAddInProgress=!1,gamificationGiftRemoveInProgress=!1;class GamificationBar extends HTMLElement{constructor(){super(),this.onCartChangedListener=this.onCartChanged.bind(this),this.onDrawerRefreshedListener=this.onDrawerRefreshed.bind(this),this.onGiftChoiceChangedListener=this.onGiftChoiceChanged.bind(this),this.onGiftChoiceClickedListener=this.onGiftChoiceClicked.bind(this),this.onGiftSubmitListener=this.onGiftSubmit.bind(this),this.onGiftVariantAddedListener=this.onGiftVariantAdded.bind(this),this.cartDrawerHost=null,this.config=this.getConfig(),this.state={totalPrice:this.config.total_price||0,hasManagedGift:this.config.gift?.has_managed_gift===!0},this.currencyFormatter=new Intl.NumberFormat(Shopify.locale,{style:"currency",currency:Shopify.currency.active})}connectedCallback(){document.addEventListener("cart:change",this.onCartChangedListener),document.addEventListener("change",this.onGiftChoiceChangedListener),document.addEventListener("click",this.onGiftChoiceClickedListener),document.addEventListener("submit",this.onGiftSubmitListener,!0),document.addEventListener("variant:add",this.onGiftVariantAddedListener),this.cartDrawerHost=this.closest("cart-drawer"),this.cartDrawerHost&&this.cartDrawerHost.addEventListener("cart-drawer:refreshed",this.onDrawerRefreshedListener),this.updateGamificationBar(),this.syncGiftChooser(),this.initializeGiftState()}disconnectedCallback(){document.removeEventListener("cart:change",this.onCartChangedListener),document.removeEventListener("change",this.onGiftChoiceChangedListener),document.removeEventListener("click",this.onGiftChoiceClickedListener),document.removeEventListener("submit",this.onGiftSubmitListener,!0),document.removeEventListener("variant:add",this.onGiftVariantAddedListener),this.cartDrawerHost&&this.cartDrawerHost.removeEventListener("cart-drawer:refreshed",this.onDrawerRefreshedListener),this.cartDrawerHost=null}async initializeGiftState(){const cart=await fetchCart;this.state.totalPrice=cart.total_price||0,!await this.maybeRemoveStaleGift(cart)&&(await this.syncManagedGiftState(cart),await this.maybeRemoveGift(cart),await this.maybeAutoAddGift(cart))}parseJSON(selector,fallback){const element=this.querySelector(selector);if(!element)return fallback;try{return JSON.parse(element.textContent.trim())}catch{return fallback}}getConfig(){return this.parseJSON("[data-gamification-config]",{modal_id:"",total_price:0,thresholds:{shipping:0,gift:0,first:0,second:0,first_type:"",second_type:""},messages:{before:"",after_first:"",after_second:""},gift:{product_count:0,requires_choice:!1,has_managed_gift:!1,products:[]}})}getGiftModal(){return document.getElementById(this.config.modal_id)}async syncManagedGiftState(cart){cart??=await fetchCart,this.state.hasManagedGift=this.getManagedGiftItems(cart).length>0,this.updateGamificationBar(),this.syncGiftChooser()}updateGamificationBar(){const totalPrice=this.state.totalPrice,thresholds=this.config.thresholds,giftConfig=this.config.gift,progressElement=this.querySelector(".gamification-bar__progress"),messageElement=this.querySelector(".gamification-bar__message"),firstMilestone=this.querySelector('[data-milestone="first"]'),secondMilestone=this.querySelector('[data-milestone="second"]'),giftActionsElement=this.querySelector(".gamification-bar__actions"),giftChoiceModal=this.getGiftModal();if(progressElement&&thresholds.second>0&&(progressElement.style.width=`${Math.min(100,Math.max(0,totalPrice/thresholds.second*100))}%`),messageElement){const remainingAmount=totalPrice>=thresholds.second?0:totalPrice>=thresholds.first?thresholds.second-totalPrice:thresholds.first-totalPrice;messageElement.innerHTML=this.getMessageTemplate().replace(/\{\{\s*remaining_amount\s*\}\}/g,this.formatRemainingAmount(remainingAmount))}this.updateMilestone(firstMilestone,thresholds.first,thresholds.first_type),this.updateMilestone(secondMilestone,thresholds.second,thresholds.second_type),giftActionsElement&&(giftActionsElement.hidden=!(giftConfig.requires_choice&&giftConfig.product_count>0&&totalPrice>=thresholds.gift&&!this.state.hasManagedGift)),giftChoiceModal?.open&&(this.state.hasManagedGift||totalPrice<thresholds.gift)&&giftChoiceModal.hide(),this.updateFooterMessage(totalPrice)}updateFooterMessage(totalPrice){const shippingTextDrawerFooter=document.getElementById("shipping-text-drawer-footer");shippingTextDrawerFooter&&(totalPrice>=this.config.thresholds.shipping?shippingTextDrawerFooter.innerHTML=shippingTextDrawerFooter.getAttribute("data-reached-message"):shippingTextDrawerFooter.innerHTML=shippingTextDrawerFooter.getAttribute("data-unreached-message"))}updateMilestone(milestoneElement,threshold,type){if(!milestoneElement)return;const iconState=this.state.totalPrice>=threshold?"reached":type==="gift"?"gift":"shipping",iconTemplate=this.querySelector(`template[data-icon="${iconState}"]`);iconTemplate&&(milestoneElement.innerHTML=iconTemplate.innerHTML)}getMessageTemplate(){return this.state.totalPrice>=this.config.thresholds.second?this.config.messages.after_second||"":this.state.totalPrice>=this.config.thresholds.first?this.config.messages.after_first||"":this.config.messages.before||""}
1formatRemainingAmount(amount){return this.currencyFormatter.format(Math.max(0,amount)/100).replace(/\$/g,"$$$$")}getGiftProductById(productId){return(this.config.gift.products||[]).find(giftProduct=>`${giftProduct.id}`==`${productId}`)}getGiftOptionLabel(input){const optionLabelElement=input.nextElementSibling;return optionLabelElement?.getAttribute("data-option-value")||optionLabelElement?.getAttribute("data-tooltip")||optionLabelElement?.textContent?.trim()||""}getSelectedGiftOptionValues(container){return Array.from(container.querySelectorAll("input[data-option-position]:checked")).sort((a,b)=>parseInt(a.getAttribute("data-option-position"))-parseInt(b.getAttribute("data-option-position"))).map(input=>({position:parseInt(input.getAttribute("data-option-position")),value:this.getGiftOptionLabel(input)}))}getMatchingGiftVariant(productData,selectedOptionValues){return productData?.variants?.find(variant=>selectedOptionValues.every(({position,value})=>`${variant[`option${position}`]||""}`===value))}getSelectedGiftChoiceItem(){const giftChoiceModal=this.getGiftModal();return giftChoiceModal?giftChoiceModal.querySelector("[data-gift-product-radio]:checked")?.closest("[data-gift-choice-item]")||giftChoiceModal.querySelector("[data-gift-choice-item]"):null}syncGiftChooser(){const giftChoiceModal=this.getGiftModal();if(!giftChoiceModal)return;const giftChoiceItems=Array.from(giftChoiceModal.querySelectorAll("[data-gift-choice-item]")),selectedGiftChoiceItem=this.getSelectedGiftChoiceItem();giftChoiceItems.forEach(giftChoiceItem=>{const isSelected=giftChoiceItem===selectedGiftChoiceItem;giftChoiceItem.classList.toggle("is-selected",isSelected);const radioInput=giftChoiceItem.querySelector("[data-gift-product-radio]");radioInput&&(radioInput.checked=isSelected)}),this.syncGiftChoiceItem(selectedGiftChoiceItem)}syncGiftChoiceItem(giftChoiceItem){const giftChoiceModal=this.getGiftModal(),giftSubmitForm=giftChoiceModal?.querySelector("[data-gift-submit-form] form"),giftSubmitButton=giftChoiceModal?.querySelector("[data-gift-shared-submit]");if(!giftChoiceItem||!giftSubmitForm||!giftSubmitButton)return;const productData=this.getGiftProductById(giftChoiceItem.getAttribute("data-gift-product-id"));if(!productData)return;const selectedOptionValues=this.getSelectedGiftOptionValues(giftChoiceItem),matchingVariant=productData.has_only_default_variant?productData.variants.find(variant=>`${variant.id}`==`${productData.selected_variant_id}`)||productData.variants[0]:this.getMatchingGiftVariant(productData,selectedOptionValues),variantIdInput=giftSubmitForm.querySelector("[data-gift-shared-variant-id]"),giftProductPropertyInput=giftSubmitForm.querySelector("[data-gift-shared-product-id]"),giftVariantPropertyInput=giftSubmitForm.querySelector("[data-gift-shared-variant-property]"),comparePriceElement=giftChoiceItem.querySelector("[data-gift-compare-price]");if(selectedOptionValues.forEach(({position,value})=>{const selectedOptionElement=giftChoiceItem.querySelector(`[data-gift-selected-option="${position}"]`);selectedOptionElement&&(selectedOptionElement.textContent=value)}),!matchingVariant){giftSubmitButton.disabled=!0;return}variantIdInput&&(variantIdInput.value=`${matchingVariant.id}`),giftProductPropertyInput&&(giftProductPropertyInput.value=`${productData.id}`),giftVariantPropertyInput&&(giftVariantPropertyInput.value=`${matchingVariant.id}`),comparePriceElement&&(comparePriceElement.textContent=this.currencyFormatter.format((matchingVariant.compare_at_price||matchingVariant.price||0)/100)),this.updateGiftChoiceImage(giftChoiceItem,productData,matchingVariant),giftSubmitButton.disabled=!matchingVariant.available||this.state.hasManagedGift||this.state.totalPrice<this.config.thresholds.gift}updateGiftChoiceImage(giftChoiceItem,productData,matchingVariant){const giftImageElement=giftChoiceItem.querySelector("[data-gift-image-wrapper] img");if(!giftImageElement)return;const imageSource=matchingVariant?.featured_image||productData.featured_image,imageAlt=matchingVariant?.featured_image_alt||productData.featured_image_alt||productData.title||"";imageSource&&(giftImageElement.src=imageSource,giftImageElement.srcset=`${imageSource} 360w`,giftImageElement.alt=imageAlt)}getAutoAddGiftVariantId(){const giftProducts=this.config.gift.products||[];
1if(giftProducts.length!==1)return"";const giftProduct=giftProducts[0];if(!giftProduct||!giftProduct.has_only_default_variant||!giftProduct.variants?.length)return"";const giftVariant=giftProduct.variants[0];return giftVariant?.available?`${giftVariant.id}`:""}getAutoGiftDismissStorageKey(){const autoAddGiftVariantId=this.getAutoAddGiftVariantId();return!autoAddGiftVariantId||this.config.gift.requires_choice?"":`gamification:auto-gift-dismissed:${autoAddGiftVariantId}:${this.config.thresholds.gift}`}isAutoGiftDismissed(){const storageKey=this.getAutoGiftDismissStorageKey();if(!storageKey)return!1;try{return window.sessionStorage.getItem(storageKey)==="true"}catch{return!1}}setAutoGiftDismissed(){const storageKey=this.getAutoGiftDismissStorageKey();if(storageKey)try{window.sessionStorage.setItem(storageKey,"true")}catch{}}clearAutoGiftDismissed(){const storageKey=this.getAutoGiftDismissStorageKey();if(storageKey)try{window.sessionStorage.removeItem(storageKey)}catch{}}syncAutoGiftDismissState(cart,previouslyHadManagedGift){if(!this.getAutoAddGiftVariantId()||this.config.gift.requires_choice)return;const hasManagedGiftNow=this.getManagedGiftItems(cart).length>0;if((cart.total_price||0)<this.config.thresholds.gift){this.clearAutoGiftDismissed();return}previouslyHadManagedGift&&!hasManagedGiftNow&&!gamificationGiftRemoveInProgress&&this.setAutoGiftDismissed()}getStaleManagedGiftItems(cart){const configuredProducts=this.config.gift.products||[],configuredProductIds=new Set(configuredProducts.map(product=>`${product.id}`)),configuredVariantIds=new Set(configuredProducts.flatMap(product=>(product.variants||[]).map(variant=>`${variant.id}`)));return this.getManagedGiftItems(cart).filter(item=>{const productId=`${item.product_id||item.properties?._gift_product_id||""}`,variantId=`${item.variant_id||item.id||item.properties?._gift_variant_id||""}`;return!configuredProductIds.has(productId)&&!configuredVariantIds.has(variantId)})}async maybeRemoveStaleGift(cart){cart??=await fetchCart;const staleManagedGiftItems=this.getStaleManagedGiftItems(cart);return staleManagedGiftItems.length===0||gamificationGiftRemoveInProgress?!1:(await Promise.all(staleManagedGiftItems.map(giftItem=>this.removeGiftFromCart(giftItem.key))),!0)}async maybeAutoAddGift(cart){cart??=await fetchCart;const autoAddGiftVariantId=this.getAutoAddGiftVariantId();!this.config.thresholds.gift||!autoAddGiftVariantId||this.config.gift.requires_choice||this.state.totalPrice<this.config.thresholds.gift||gamificationGiftAddInProgress||this.isAutoGiftDismissed()||this.getManagedGiftItems(cart).length>0||await this.addGiftToCart(autoAddGiftVariantId,this.config.thresholds.gift)}async maybeRemoveGift(cart){cart??=await fetchCart;const managedGiftItems=this.getManagedGiftItems(cart);!this.config.thresholds.gift||this.state.totalPrice>=this.config.thresholds.gift||managedGiftItems.length===0||gamificationGiftRemoveInProgress||await Promise.all(managedGiftItems.map(giftItem=>this.removeGiftFromCart(giftItem.key)))}getManagedGiftItems(cart){return(cart.items||[]).filter(item=>item.properties?._gift_source==="gamification_bar")}async addGiftToCart(variantId,giftThreshold){gamificationGiftAddInProgress=!0,document.documentElement.dispatchEvent(new CustomEvent("theme:loading:start",{bubbles:!0}));let sectionsToBundle=[];document.documentElement.dispatchEvent(new CustomEvent("cart:prepare-bundled-sections",{bubbles:!0,detail:{sections:sectionsToBundle}}));try{const response=await fetch(`${Shopify.routes.root}cart/add.js`,{body:JSON.stringify({items:[{id:parseInt(variantId),quantity:1,properties:{_gift_source:"gamification_bar",_gift_threshold:`${giftThreshold}`,_gift_variant_id:`${variantId}`}}],sections:sectionsToBundle,sections_url:window.location.pathname}),method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"}}),responseJson=await response.json();if(document.documentElement.dispatchEvent(new CustomEvent("theme:loading:end",{bubbles:!0})),!response.ok){document.dispatchEvent(new CustomEvent("cart:refresh"));return}if(window.themeVariables.settings.cartType==="page"||window.themeVariables.settings.pageType==="cart"){window.location.href=`${Shopify.routes.root}cart`;return}const cartContent=await(await fetch(`${Shopify.routes.root}cart.js`)).json();cartContent.sections=responseJson.sections,document.documentElement.dispatchEvent(new CustomEvent("cart:change",{bubbles:!0,detail:{baseEvent:"variant:add",cart:cartContent}}))}
1finally{gamificationGiftAddInProgress=!1}}async removeGiftFromCart(lineKey){gamificationGiftRemoveInProgress=!0,document.documentElement.dispatchEvent(new CustomEvent("theme:loading:start",{bubbles:!0}));let sectionsToBundle=[];document.documentElement.dispatchEvent(new CustomEvent("cart:prepare-bundled-sections",{bubbles:!0,detail:{sections:sectionsToBundle}}));try{const response=await fetch(`${Shopify.routes.root}cart/change.js`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:lineKey,quantity:0,sections:sectionsToBundle.join(",")})});if(document.documentElement.dispatchEvent(new CustomEvent("theme:loading:end",{bubbles:!0})),!response.ok){document.dispatchEvent(new CustomEvent("cart:refresh"));return}const cartContent=await response.json();if(window.themeVariables.settings.pageType==="cart"){window.location.reload();return}document.documentElement.dispatchEvent(new CustomEvent("cart:change",{bubbles:!0,detail:{baseEvent:"line-item:change",cart:cartContent}}))}finally{gamificationGiftRemoveInProgress=!1}}async onCartChanged(event){const cart=event.detail.cart,previouslyHadManagedGift=this.state.hasManagedGift;this.state.totalPrice=cart.total_price||0,!await this.maybeRemoveStaleGift(cart)&&(this.syncAutoGiftDismissState(cart,previouslyHadManagedGift),await this.syncManagedGiftState(cart),await this.maybeRemoveGift(cart),await this.maybeAutoAddGift(cart))}async onDrawerRefreshed(){const cart=await fetchCart,previouslyHadManagedGift=this.state.hasManagedGift;this.state.totalPrice=cart.total_price||0,!await this.maybeRemoveStaleGift(cart)&&(this.syncAutoGiftDismissState(cart,previouslyHadManagedGift),await this.syncManagedGiftState(cart),this.updateGamificationBar(),this.syncGiftChooser(),await this.maybeRemoveGift(cart),await this.maybeAutoAddGift(cart))}onGiftChoiceChanged(event){if(!event.target.matches("input[data-option-position], [data-gift-product-radio]"))return;const giftChoiceItem=event.target.closest("[data-gift-choice-item]");!giftChoiceItem||giftChoiceItem.getAttribute("data-gift-modal-id")!==this.config.modal_id||this.syncGiftChooser()}onGiftChoiceClicked(event){const giftChoiceItem=event.target.closest("[data-gift-choice-item]");if(!giftChoiceItem||giftChoiceItem.getAttribute("data-gift-modal-id")!==this.config.modal_id)return;const radioInput=giftChoiceItem.querySelector("[data-gift-product-radio]");!radioInput||radioInput.checked||(radioInput.checked=!0,this.syncGiftChooser())}onGiftSubmit(event){const giftSubmitForm=event.target.closest("[data-gift-submit-form]");!giftSubmitForm||giftSubmitForm.getAttribute("data-gift-modal-id")!==this.config.modal_id||(this.state.hasManagedGift||this.state.totalPrice<this.config.thresholds.gift)&&(event.preventDefault(),event.stopPropagation(),this.syncGiftChooser())}onGiftVariantAdded(event){const giftSubmitForm=event.target.closest("[data-gift-submit-form]");!giftSubmitForm||giftSubmitForm.getAttribute("data-gift-modal-id")!==this.config.modal_id||this.getGiftModal()?.hide()}}window.customElements.get("gamification-bar")||window.customElements.define("gamification-bar",GamificationBar)})();
2//# sourceMappingURL=/cdn/shop/t/120/assets/gamification.js.map?v=90429056084692690441784219852

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.