import{Segment}from"@dna/analytics";import{client}from"@dna/constructor";import{RespondToViewport,WithProfiler}from"@dna/mixins";import*as paths from"@dna/paths";import styles from"@dna/styles";import{getSectionPosition,igGetExperimentControl,igReady,t}from"@dna/utils";import{LitElement,classMap,createRef,css,html,nothing,ref,when}from"@lit";try{window?.performance?.measure("component-constructor-results",{start:"rothys.script.component-constructor-results.start",detail:{devtools:{trackGroup:"Rothys",track:"Script Loading"}}})}catch(e){console.error(e)}const TaskStatus={PENDING:"PENDING",LOADING:"LOADING",COMPLETE:"COMPLETE",ERROR:"ERROR"},cleanedSearchQuery=query=>query?query.replace(/[\/\\]/g,""):"";class DNAConstructorResults extends WithProfiler(RespondToViewport(LitElement)){static properties={searchTerm:{type:String},isSearch:{type:Boolean,attribute:"is-search"},collectionHandle:{type:String,attribute:"collection-handle"},showFilters:{type:Boolean,attribute:"show-filters"},showPagination:{type:Boolean,attribute:"show-pagination"},showSort:{type:Boolean,attribute:"show-sort"},resultsPerPage:{type:Number,attribute:"results-per-page"},showCardCarousels:{type:Boolean,attribute:"show-card-carousels",reflect:!0},enableHoverImage:{type:Boolean,attribute:"enable-hover-image",reflect:!0},quickAdd:{type:Boolean,attribute:"quick-add"},quickView:{type:Boolean,attribute:"quick-view"},filtersOpen:{type:Boolean,attribute:"filters-open",reflect:!0},inGrids:{type:Array},status:{type:String},startedInitialLoad:{type:Boolean},sectionID:{type:String,attribute:"section-id"},fitTips:{type:Array},hidePriceControlOptions:{type:Boolean},hasRenderedSchema:{type:Boolean},navOpen:{type:Boolean,state:!0},allProducts:{type:Array,state:!0},experimentationTrackingKey:{type:String,attribute:"experimentation-tracking-key"},trackingKey:{type:String,attribute:"tracking-key"},hideProductColorCount:{type:Boolean,attribute:"hide-product-color-count",reflect:!0},showEditorialAltImage:{type:Boolean,attribute:"show-editorial-alt-image",reflect:!0}};constructor(){super(),performance.mark("component-constructor-results-start"),this.router=__DNA_GLOBAL__.utils.queryRouter,this._setMobileBreakpoints(["mobile","tablet"]);const query=this.router.query.get();this.searchTerm=cleanedSearchQuery(query?.q?.[0])??__DNA_GLOBAL__?.constructor?.searchTerm,this.showFilters=!1,this.showPagination=!1,this.showSort=!1,this.resultsPerPage=__DNA_GLOBAL__?.constructor?.resultsPerPage,this.searchResultsPerPage=__DNA_GLOBAL__?.constructor?.searchResultsPerPage,this.isSearch=__DNA_GLOBAL__?.constructor?.isSearch??!1,this.collectionHandle=__DNA_GLOBAL__?.constructor?.collectionHandle??"",this.inGrids=[],this.results=null,this.status=TaskStatus.PENDING,this.filtersOpen=!1,this.navOpen=!0,this.topBarRef=createRef(),this.startedInitialLoad=!1,this.cartItems=[],this.sectionID="",this.fitTips=[],this.hidePriceControlOptions=!1,this.hasRenderedSchema=!1,this.allProducts=[],this.rafID=null,this.showMoreClicked=!1,this.queryParams=this.router.query.get(),this.sortTriggered=!1,this.applyTest1368=!1,this.filterBarRef=createRef();const params=this.router.query.getNormalized(),pageNum=Array.isArray(params.page)?Number.parseInt(params.page[0]):Number.parseInt(params.page);this.currentPage=pageNum||1,(this.collectionHandle||this.isSearch)&&this.loadInitialResults()}connectedCallback(){super.connectedCallback(),this.$section=this.closest(".shopify-section"),this.sectionPosition=getSectionPosition(this.$section),igReady.then(async()=>{await igGetExperimentControl({staging:"295da21f-8686-45f9-af3e-4bcba4c92194",production:"1b257090-860c-460c-ac39-ef43b5e72408"})||(this.applyTest1368=!0)}),this.applyTest1368||(document.addEventListener("dna:main-menu:show",this._handleNavShow),document.addEventListener("dna:main-menu:hide",this._handleNavHide)),window.addEventListener("scroll",this._handleScroll,{passive:!0}),this.currentPage>1&&history.scrollRestoration&&(history.scrollRestoration="manual"),this.io=new IntersectionObserver(entries=>{for(const entry of entries)this.handleObserverEntry(entry)},{root:null,rootMargin:"0px",threshold:.5})}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("dna:main-menu:show",this._handleNavShow),document.removeEventListener("dna:main-menu:hide",this._handleNavHide),window.removeEventListener("scroll",this._handleScroll)}async showMoreRef(ref2){ref2?(await ref2.updateComplete,this.io.observe(ref2)):this.io.disconnect()}handleObserverEntry(entry){entry.isIntersecting&&this.prefetchProductsObserver()}async prefetchProductsObserver(){this.prefetchedResults instanceof Promise||await this.prefetchProducts()}_handleNavShow=()=>{this.navOpen=!0};_handleNavHide=()=>{this.navOpen=!1};_handleScroll=()=>{this.rafID===null&&(this.rafID=requestAnimationFrame(()=>{this.rafID=null,this.currentPage>1&&this.status===TaskStatus.COMPLETE&&sessionStorage.setItem("rothys_scroll_position",window.scrollY)}))};firstUpdated(){super.firstUpdated(),this.startedInitialLoad||this.loadInitialResults(),this.router?.events?.addEventListener("queryChange",event=>{const updatedParams=this.router.query.get(),sortEqual=this.queryParams?.sort?.[0]===updatedParams?.sort?.[0],sortByEqual=this.queryParams?.sort_order?.[0]===updatedParams?.sort_order?.[0];this.sortTriggered=!(sortEqual&&sortByEqual),this.showMoreClicked||(this.sortTriggered||(this.allProducts=[]),this.prefetchedResults=null,this.currentPage=1),this.fetchProducts(),this.showMoreClicked=!1,this.queryParams=updatedParams}),document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>{this.status===TaskStatus.COMPLETE&&this.dispatchEvent(new CustomEvent("dna:constructor-results:loaded",{detail:this.results,bubbles:!0}))},0)}),document.querySelector(":root")?.style.setProperty("--dna-filter-bar-height",this.filterBarRef?.value?`${this.filterBarRef.value.getBoundingClientRect().height}px`:"0px")}updateResults(results){this.results=results,this.sortTriggered?this.allProducts=results.products:this.allProducts.push(...results.products),this.status=TaskStatus.COMPLETE,this.dispatchEvent(new CustomEvent("dna:constructor-results:loaded",{detail:results,bubbles:!0})),performance.mark("component-constructor-results-end");try{performance.measure("component-constructor-results",{start:"component-constructor-results-start",end:"component-constructor-results-end",detail:{devtools:{track:"Constructor",trackGroup:"Rothys",properties:[["Collection Handle",this.collectionHandle]]}}})}catch(e){console.error(e)}}async loadInitialResults(){if(this.startedInitialLoad=!0,__DNA_GLOBAL__?.constructor?.prefetchPromise instanceof Promise){console.log("CIO Prefetch promise was found"),this.dispatchEvent(new CustomEvent("dna:load:start"));const result=await __DNA_GLOBAL__.constructor?.prefetchPromise;this.updateResults(result)}else console.log("CIO Prefetch promise was not found"),this.fetchProducts(!0)}async prefetchProducts(){try{const response2=this.isSearch?await this.searchQuery(!0):await this.browseQuery(!0);this.prefetchedResults=Promise.resolve(response2)}catch(err){console.error("Error preloading results:",err)}}toggleFilters(){this.filtersOpen=!this.filtersOpen,this.filtersOpen?(this.querySelector("dna-grid-filters")?.focus(),this.trackFiltersViewed()):this?.focus()}async searchQuery(isPrefetching=!1,isInitialLoad=!1){const params=this.router.query.getNormalized();if(isInitialLoad){const fetchPromises=[];for(let page=1;page<=this.currentPage;page++){const pageParams={...params,page};fetchPromises.push(client.getSearchResults(this.searchTerm,pageParams))}const allResults=await Promise.all(fetchPromises);return{...allResults[0],products:allResults.flatMap(result=>result.products)}}return params.page=isPrefetching?this.currentPage+1:params.page||this.currentPage,await client.getSearchResults(this.searchTerm,{...params,resultsPerPage:this.searchResultsPerPage})}async browseQuery(isPrefetching=!1,isInitialLoad=!1){const params=this.router.query.getNormalized();if(isInitialLoad){const fetchPromises=[];for(let page=1;page<=this.currentPage;page++){const pageParams={...params,page};fetchPromises.push(client.getBrowseProducts(this.collectionHandle,pageParams))}const allResults=await Promise.all(fetchPromises);return{...allResults[0],products:allResults.flatMap(result=>result.products)}}return params.page=isPrefetching?this.currentPage+1:params.page||this.currentPage,await client.getBrowseProducts(this.collectionHandle,{...params,resultsPerPage:this.resultsPerPage})}fetchProducts=async(isInitialProducts=!1)=>{this.status=TaskStatus.LOADING;try{let response2,shouldScrollToTop;this.prefetchedResults instanceof Promise?(response2=await this.prefetchedResults,this.prefetchedResults=null):(this.dispatchEvent(new CustomEvent("dna:load:start")),response2=this.isSearch?await this.searchQuery(!1,isInitialProducts):await this.browseQuery(!1,isInitialProducts),shouldScrollToTop=!0),this.updateResults(response2),this.prefetchedResults=null,this.topBarRef.value&&shouldScrollToTop&&this.topBarRef.value.scrollIntoView({behavior:"smooth"})}catch(err){throw console.error("Error fetching results:",err),this.status=TaskStatus.ERROR,new Error(response)}};clearAllFilters(){const queryData=this.router.query.get(),filtersObj=Object.keys(queryData).filter(key=>key.startsWith("filter.")).reduce((acc,key)=>(acc[key]=null,acc),{});this.router.query.update(filtersObj),this.trackFiltersCleared()}get products(){return this.allProducts||[]}get totalCount(){return this.results?.meta?.totalCount||void 0}get filters(){return this.results?.filters||[]}get activeFilters(){return this.filters.map(filter=>({...filter,options:void 0,selectedOptions:Array.isArray(filter?.options)?filter.options.filter(option=>option.status==="selected"):[]}))}get activeSelectedFilters(){return this.activeFilters.filter(filter=>filter.selectedOptions.length>0)}get sort(){if(!this.results?.sort)return{options:[],selected:""};const selected=this.results?.sort?.selected;return{options:this.results?.sort?.options||[],selected:`${selected.sort_by}|${selected.sort_order}`}}get totalResults(){return this.results?.pagination?.totalResults}get selectedOptionsValues(){return this.activeFilters.flatMap(filter=>filter.selectedOptions)}get mobileFilterButtonText(){return this.totalCount===0?"See Products":`See ${this.totalCount} Product${this.totalCount>1?"s":""}`}get searchandising(){return this.results?.searchandising}showMore(){this.showMoreScrollPosition=window.scrollY,this.showMoreClicked=!0,this.router.query.update({page:this.currentPage+1}),this.currentPage=this.currentPage+1}removeFilterOption(filter,option){this.router.query.remove({[`filter.${filter?.name}`]:option.value}),this.trackFilterRemoved({filter_name:option?.name?.toLowerCase(),filter_type:filter?.display_name?.toLowerCase()})}trackFiltersViewed(){Segment.protect(()=>{Segment.track(Segment.CONSTANTS.EVENTS.FILTERS_VIEWED)})}trackFiltersCleared(){Segment.protect(()=>{Segment.track(Segment.CONSTANTS.EVENTS.FILTERS_CLEARED)})}trackFilterRemoved(filterData){Segment.protect(()=>{Segment.track(Segment.CONSTANTS.EVENTS.FILTER_REMOVED,filterData)})}_renderSchema(){if(this.products.length>0&&!this.hasRenderedSchema){const scriptContent={"@context":"http://schema.org/","@type":"ItemList",itemListElement:this.products.map((product,index)=>({"@type":"ListItem",position:index+1,item:{"@type":"Product",name:product.title,url:`${window.location.origin}${Shopify.routes.root}products/${product.handle}`,image:product.media.filter(media=>media.type==="image").slice(0,3).map(media=>media.url),...product.metafields?.yotpo?.reviews_average>0&&product.metafields?.yotpo?.reviews_count>0?{aggregateRating:{"@type":"AggregateRating",ratingValue:product.metafields?.yotpo?.reviews_average,reviewCount:product.metafields?.yotpo?.reviews_count}}:{},offers:{"@type":"Offer",price:product.prices[Shopify.country],priceCurrency:window.Shopify.currency.active,...product.compareAtPrices[Shopify.country]&&product.compareAtPrices[Shopify.country]>product.prices[Shopify.country]?{priceSpecification:{"@type":"UnitPriceSpecification",priceType:"https://schema.org/ListPrice",price:product.compareAtPrices[Shopify.country],priceCurrency:window.Shopify.currency.active}}:{}}}}))},scriptElement=document.createElement("script");scriptElement.type="application/ld+json",scriptElement.textContent=JSON.stringify(scriptContent),document.head.appendChild(scriptElement),this.hasRenderedSchema=!0}}_renderPagination=()=>{const currentTotalAmount=this.products.length,totalResults=this.totalResults,updatedProgress=currentTotalAmount/totalResults*100;return html`
Loading...