class PredictiveSearch extends HTMLElement{constructor(){super(),this.cachedResults={},this.input=this.querySelector('input[type="search"]'),this.predictiveSearchResults=this.querySelector("[data-predictive-search]"),this.trendingAndProductsBlock=this.querySelector("[data-quick-trending-products]"),this.closeStickySearchButton=document.querySelector(".header-search-close"),this.productToShow=this.dataset.productToShow,this.searchDetails=this.querySelector(".search_details"),this.predictiveSearch=this.querySelector("predictive-search"),this.isOpen=!1,this.quickSearchTrending=this.querySelectorAll(".quickSearchTrending .link"),this.searchResultsWidget=this.getElementsByClassName("quickSearchResultsWidget")[0],this.setupEventListeners(),this.quickSearchTrending.forEach(element=>{element.addEventListener("click",this.quickSearchTrendingClick.bind(this))})}setupEventListeners(){this.querySelector("form.search").addEventListener("submit",this.onFormSubmit.bind(this)),this.input.addEventListener("input",debounce(event=>{this.onChange(event)},500).bind(this)),this.input.addEventListener("focus",this.onFocus.bind(this)),this.addEventListener("focusout",this.onFocusOut.bind(this)),this.addEventListener("keyup",this.onKeyup.bind(this)),this.addEventListener("keydown",this.onKeydown.bind(this)),document.addEventListener("click",this.onDocClick.bind(this)),this.closeStickySearchButton!=null&&this.closeStickySearchButton.addEventListener("click",this.onCloseStickySearchClick.bind(this)),this.input.addEventListener("click",this.doBeforeQuickSearchProduct.bind(this)),window.innerWidth<=1024&&document.querySelector("[data-search-mobile]")&&document.querySelectorAll("[data-search-mobile]").forEach(button=>{button.addEventListener("click",this.doBeforeQuickSearchProduct.bind(this))})}doBeforeQuickSearchProduct(){this.renderQuickSearchProductBlock()}renderQuickSearchProductBlock(){if(!this.searchResultsWidget.classList.contains("ajax-loaded")){const block=this.searchResultsWidget.querySelector(".quickSearchProduct");let url=block?.getAttribute("data-collection"),limit=block?.getAttribute("data-limit"),sectionId="list-result-block";if(url!=null&&url!=null)$.ajax({type:"GET",url:window.routes.root+"/collections/"+url,cache:!1,data:{view:"ajax_product_block",constraint:`limit=${limit}+sectionId=${sectionId}`},beforeSend:()=>{block.closest(".quickSearchResultsWidget").classList.add("ajax-loaded")},success:data=>{if(url!=""){const dataRes=this.handleResponse(data,limit);block.querySelector(".products-grid").innerHTML=dataRes}window.sharedFunctions?.swapHoverVideoProductCard()},complete:()=>{if(window.show_multiple_currencies&&Currency.currentCurrency!=window.shop_currency||window.show_auto_currency){let currencyCode=document.getElementById("currencies")?.querySelector(".active")?.getAttribute("data-currency");Currency.convertAll(window.shop_currency,currencyCode,"span.money","money_format")}}});else if(this.searchResultsWidget.classList.add("ajax-loaded"),window.show_multiple_currencies&&Currency.currentCurrency!=window.shop_currency||window.show_auto_currency){let currencyCode=document.getElementById("currencies")?.querySelector(".active")?.getAttribute("data-currency");Currency.convertAll(window.shop_currency,currencyCode,"span.money","money_format")}}}handleResponse(data,limit){let htmlMedia=document.createElement("div");return htmlMedia.innerHTML=data,$(htmlMedia).find(`.product:nth-child(n+${Number(limit)+1})`).remove(),$(htmlMedia).html()}getQuery(){return this.input.value.trim()}onChange(){const searchTerm=this.getQuery();if(!searchTerm.length){this.close(!0);return}this.getSearchResults(searchTerm)}onFormSubmit(event){(!this.getQuery().length||this.querySelector('[aria-selected="true"] a'))&&event.preventDefault()}onFocus(){const searchTerm=this.getQuery();if(!searchTerm.length)return this.showTrendingAndProducts();this.getAttribute("results")==="true"?this.open():this.getSearchResults(searchTerm)}onFocusOut(){setTimeout(()=>{this.contains(document.activeElement)||this.close()})}onKeyup(event){switch(this.getQuery().length||(this.close(!0),this.showTrendingAndProducts()),event.preventDefault(),event.code){case"ArrowUp":this.switchOption("up");break;case"ArrowDown":this.switchOption("down");break;case"Enter":this.selectOption();break}}onKeydown(event){(event.code==="ArrowUp"||event.code==="ArrowDown")&&event.preventDefault()}switchOption(direction){if(!this.getAttribute("open"))return;const moveUp=direction==="up",selectedElement=this.querySelector('[aria-selected="true"]'),allElements=this.querySelectorAll("li");let activeElement=this.querySelector("li");moveUp&&!selectedElement||(this.statusElement.textContent="",!moveUp&&selectedElement?activeElement=selectedElement.nextElementSibling||allElements[0]:moveUp&&(activeElement=selectedElement.previousElementSibling||allElements[allElements.length-1]),activeElement!==selectedElement&&(activeElement.setAttribute("aria-selected",!0),selectedElement&&selectedElement.setAttribute("aria-selected",!1),this.setLiveRegionText(activeElement.textContent),this.input.setAttribute("aria-activedescendant",activeElement.id)))}selectOption(){const selectedProduct=this.querySelector('[aria-selected="true"] a, [aria-selected="true"] button');selectedProduct&&selectedProduct.click()}getSearchResults(searchTerm){const queryKey=searchTerm.replace(" ","-").toLowerCase();if(this.setLiveRegionLoadingState(),this.cachedResults[queryKey]){this.renderSearchResults(this.cachedResults[queryKey]),this.updateViewAllLink(searchTerm);return}fetch(`${routes.predictive_search_url}?q=${encodeURIComponent(searchTerm)}&${encodeURIComponent("resources[type]")}=product&${encodeURIComponent("resources[limit]")}=${this.productToShow}§ion_id=predictive-search`).then(response=>{if(!response.ok){var error=new Error(response.status);throw this.close(),error}return response.text()}).then(text=>{const resultsMarkup=new DOMParser().parseFromString(text,"text/html").querySelector("#shopify-section-predictive-search").innerHTML;this.cachedResults[queryKey]=resultsMarkup,this.renderSearchResults(resultsMarkup),this.updateViewAllLink(searchTerm)}).catch(error=>{throw this.close(),error})}setLiveRegionLoadingState(){this.statusElement=this.statusElement||this.querySelector(".predictive-search-status"),this.loadingText=this.loadingText||this.getAttribute("data-loading-text"),this.setLiveRegionText(this.loadingText),this.setAttribute("loading",!0)}setLiveRegionText(statusText){this.statusElement.setAttribute("aria-hidden","false"),this.statusElement.textContent=statusText,setTimeout(()=>{this.statusElement.setAttribute("aria-hidden","true")},1e3)}renderSearchResults(resultsMarkup){this.predictiveSearchResults.innerHTML=resultsMarkup,this.setAttribute("results",!0),this.setAttribute("open",!0),this.setLiveRegionResults(),this.open(),this.hideTrendingAndProducts(),(window.show_multiple_currencies&&typeof Currency<"u"&&Currency.currentCurrency!=shopCurrency||window.show_auto_currency)&&Currency.convertAll(window.shop_currency,$("#currencies .active").attr("data-currency"),"span.money","money_format"),window.sharedFunctions?.swapHoverVideoProductCard()}setLiveRegionResults(){this.removeAttribute("loading"),this.setLiveRegionText(this.querySelector("[data-predictive-search-live-region-count-value]").textContent)}getResultsMaxHeight(){return this.resultsMaxHeight=window.innerHeight-document.querySelector('[class^="header-navigation"]').getBoundingClientRect().bottom,this.resultsMaxHeight}open(){this.setAttribute("open",!0),this.input.setAttribute("aria-expanded",!0),this.isOpen=!0}close(clearSearchTerm=!1){clearSearchTerm&&(this.input.value="",this.removeAttribute("results"));const selected=this.querySelector('[aria-selected="true"]');selected&&selected.setAttribute("aria-selected",!1),this.input.setAttribute("aria-activedescendant",""),this.removeAttribute("open"),this.input.setAttribute("aria-expanded",!1),this.resultsMaxHeight=!1,this.predictiveSearchResults.removeAttribute("style"),this.isOpen=!1}showTrendingAndProducts(){this.trendingAndProductsBlock&&(this.trendingAndProductsBlock.classList.add("is-show"),this.trendingAndProductsBlock.classList.remove("hidden"))}hideTrendingAndProducts(){this.trendingAndProductsBlock&&(this.trendingAndProductsBlock.classList.remove("is-show"),this.trendingAndProductsBlock.classList.add("hidden"))}onDocClick(e){const isInModal=this.contains(e.target),$target=e.target;(!isInModal||$target.closest(".header-search-popup-close")||$target.matches(".header-search-popup-close")||$target.closest(".header-search-close")||$target.matches(".header-search-close"))&&(this.close(),this.hideTrendingAndProducts())}onCloseStickySearchClick(){this.close(),this.hideTrendingAndProducts(),document.querySelector("body").classList.remove("sticky-search-open"),document.querySelector("body").classList.remove("sticky-search-menu-open"),this.closest('[class*="section-header-"]')?.classList.remove("sticky-search-menu-open"),this.closest('[class*="section-header-"]')?.classList.remove("sticky-search-menu-custom-open")}updateViewAllLink(searchTerm){const qsViewAllLink=document.querySelector("[data-qs-view-all-link]");if(!qsViewAllLink)return;const linkTotal=`${routes.search_url}?q=${encodeURIComponent(searchTerm)}&options%5Bprefix%5D=last&type=product`;return qsViewAllLink.href=linkTotal,this.getTotalResults(linkTotal).then(count=>{qsViewAllLink.innerHTML=qsViewAllLink.innerHTML.replace("()",`(${count})`)})}getTotalResults(url){return fetch(url).then(response=>{if(!response.ok){var error=new Error(response.status);throw this.close(),error}return response.text()}).then(text=>new DOMParser().parseFromString(text,"text/html").querySelector('[id^="SearchSection"]').dataset.searchCount).catch(error=>{throw this.close(),error})}quickSearchTrendingClick(event){window.location=event.currentTarget.getAttribute("href")}}customElements.define("predictive-search",PredictiveSearch); //# sourceMappingURL=/cdn/shop/t/2/assets/predictive-search.js.map?v=16579742612086828001721749077