import{Component}from"@theme/component";import{debounce,onAnimationEnd,prefersReducedMotion,onDocumentLoaded}from"@theme/utilities";import{sectionRenderer}from"@theme/section-renderer";import{morph}from"@theme/morph";import{RecentlyViewed}from"@theme/recently-viewed-products";import{DialogCloseEvent}from"@theme/dialog";class PredictiveSearchComponent extends Component{requiredRefs=["searchInput","predictiveSearchResults","resetButton"];#controller=new AbortController;#activeFetch=null;get dialog(){return this.closest("dialog-component")}connectedCallback(){super.connectedCallback();const{dialog}=this,{signal}=this.#controller;this.refs.searchInput.value.length>0&&this.#showResetButton(),dialog&&(document.addEventListener("keydown",this.#handleKeyboardShortcut,{signal}),dialog.addEventListener(DialogCloseEvent.eventName,this.#handleDialogClose,{signal}),this.addEventListener("click",this.#handleModalClick,{signal})),onDocumentLoaded(()=>{this.resetSearch(!1)})}#handleModalClick=event=>{const target=event.target;!(target instanceof HTMLButtonElement||target instanceof HTMLAnchorElement||target instanceof HTMLInputElement||target.closest("button")||target.closest("a")||target.closest("input"))&&this.refs.searchInput&&this.refs.searchInput.focus()};disconnectedCallback(){super.disconnectedCallback(),this.#controller.abort()}#handleKeyboardShortcut=event=>{event.metaKey&&event.key==="k"&&this.dialog?.toggleDialog()};#handleDialogClose=()=>{this.#resetSearch()};get#allResultsItems(){return Array.from(this.querySelectorAll(".predictive-search-results__wrapper-queries, .predictive-search-results__wrapper-products, .predictive-search-results__list")).flatMap(container=>container.classList.contains("predictive-search-results__wrapper-products")?Array.from(container.querySelectorAll(".predictive-search-results__card")):Array.from(container.querySelectorAll('[ref="resultsItems[]"], .predictive-search-results__card'))).filter(item=>item instanceof HTMLElement)}#isKeyboardNavigation=!1;get#currentIndex(){return this.#allResultsItems?.findIndex(item=>item.getAttribute("aria-selected")==="true")??-1}set#currentIndex(index){if(this.#allResultsItems?.length){this.#allResultsItems.forEach(item=>{item.classList.remove("keyboard-focus")});for(const[itemIndex,item]of this.#allResultsItems.entries())itemIndex===index?(item.setAttribute("aria-selected","true"),this.#isKeyboardNavigation&&item.classList.add("keyboard-focus"),item.scrollIntoView({behavior:prefersReducedMotion()?"instant":"smooth",block:"nearest"})):item.removeAttribute("aria-selected");this.refs.searchInput.focus()}}get#currentItem(){return this.#allResultsItems?.[this.#currentIndex]}onSearchKeyDown=event=>{if(event.key==="Escape"){this.#resetSearch();return}if(!this.#allResultsItems?.length||event.key==="ArrowLeft"||event.key==="ArrowRight")return;const currentIndex=this.#currentIndex,totalItems=this.#allResultsItems.length;switch(event.key){case"ArrowDown":this.#isKeyboardNavigation=!0,event.preventDefault(),this.#currentIndex=currentIndex0?currentIndex-1:totalItems-1):(this.#isKeyboardNavigation=!0,event.preventDefault(),this.#currentIndex=currentIndex0?currentIndex-1:totalItems-1;break;case"Enter":{const singleResultContainer=this.refs.predictiveSearchResults.querySelector("[data-single-result-url]");if(singleResultContainer instanceof HTMLElement&&singleResultContainer.dataset.singleResultUrl){event.preventDefault(),window.location.href=singleResultContainer.dataset.singleResultUrl;return}if(this.#currentIndex>=0)event.preventDefault(),this.#currentItem?.querySelector("a")?.click();else{const searchUrl=new URL(Theme.routes.search_url,location.origin);searchUrl.searchParams.set("q",this.refs.searchInput.value),window.location.href=searchUrl.toString()}break}}};clearRecentlyViewedProducts(event){event.stopPropagation(),RecentlyViewed.clearProducts();const{recentlyViewedItems,recentlyViewedTitle,recentlyViewedWrapper}=this.refs;[...recentlyViewedItems||[],...recentlyViewedTitle||[]].length!==0&&recentlyViewedWrapper&&(recentlyViewedWrapper.classList.add("removing"),onAnimationEnd(recentlyViewedWrapper,()=>{recentlyViewedWrapper.remove()}))}resetSearch=debounce((keepFocus=!0)=>{keepFocus&&this.refs.searchInput.focus(),this.#resetSearch()},100);search=debounce(event=>{if(!event.inputType)return;const searchTerm=this.refs.searchInput.value.trim();if(this.#currentIndex=-1,!searchTerm.length){this.#resetSearch();return}this.#showResetButton(),this.#getSearchResults(searchTerm)},200);#resetScrollPositions(){requestAnimationFrame(()=>{const resultsInner=this.refs.predictiveSearchResults.querySelector(".predictive-search-results__inner");resultsInner instanceof HTMLElement&&(resultsInner.scrollTop=0);const formContent=this.querySelector(".predictive-search-form__content");formContent instanceof HTMLElement&&(formContent.scrollTop=0)})}async#getSearchResults(searchTerm){if(!this.dataset.sectionId)return;const url=new URL(Theme.routes.predictive_search_url,location.origin);url.searchParams.set("q",searchTerm),url.searchParams.set("resources[limit_scope]","each");const{predictiveSearchResults}=this.refs,abortController=this.#createAbortController();sectionRenderer.getSectionHTML(this.dataset.sectionId,!1,url).then(resultsMarkup=>{resultsMarkup&&(abortController.signal.aborted||(morph(predictiveSearchResults,resultsMarkup),this.#resetScrollPositions()))}).catch(error=>{if(!abortController.signal.aborted)throw error})}async#getRecentlyViewedProductsMarkup(){if(!this.dataset.sectionId)return null;const viewedProducts=RecentlyViewed.getProducts();if(viewedProducts.length===0)return null;const url=new URL(Theme.routes.search_url,location.origin);return url.searchParams.set("q",viewedProducts.map(id=>`id:${id}`).join(" OR ")),url.searchParams.set("resources[type]","product"),sectionRenderer.getSectionHTML(this.dataset.sectionId,!1,url)}#hideResetButton(){const{resetButton}=this.refs;resetButton.hidden=!0}#showResetButton(){const{resetButton}=this.refs;resetButton.hidden=!1}#createAbortController(){const abortController=new AbortController;return this.#activeFetch&&this.#activeFetch.abort(),this.#activeFetch=abortController,abortController}#resetSearch=async()=>{const{predictiveSearchResults,searchInput}=this.refs,emptySectionId="predictive-search-empty";this.#currentIndex=-1,searchInput.value="",this.#hideResetButton();const abortController=this.#createAbortController(),emptySectionMarkup=await sectionRenderer.getSectionHTML(emptySectionId,!1),parsedEmptySectionMarkup=new DOMParser().parseFromString(emptySectionMarkup,"text/html").querySelector(".predictive-search-empty-section");if(!parsedEmptySectionMarkup)throw new Error("No empty section markup found");if(RecentlyViewed.getProducts().length>0){const recentlyViewedMarkup=await this.#getRecentlyViewedProductsMarkup();if(!recentlyViewedMarkup)return;const recentlyViewedProductsHtml=new DOMParser().parseFromString(recentlyViewedMarkup,"text/html").getElementById("predictive-search-products");if(!recentlyViewedProductsHtml)return;for(const child of recentlyViewedProductsHtml.children)child instanceof HTMLElement&&child.setAttribute("ref","recentlyViewedWrapper");const collectionElement=parsedEmptySectionMarkup.querySelector("#predictive-search-products");if(!collectionElement)return;collectionElement.prepend(...recentlyViewedProductsHtml.children)}abortController.signal.aborted||(morph(predictiveSearchResults,parsedEmptySectionMarkup),this.#resetScrollPositions())}}customElements.get("predictive-search-component")||customElements.define("predictive-search-component",PredictiveSearchComponent); //# sourceMappingURL=/cdn/shop/t/47/assets/predictive-search.js.map?v=91780268189318326841757451905