| 42 | |
| 43 | @Service() |
| 44 | export class Search { |
| 45 | readonly searchQuery = signal(''); |
| 46 | |
| 47 | private readonly config = inject(ENVIRONMENT); |
| 48 | private readonly client = inject(ALGOLIA_CLIENT); |
| 49 | |
| 50 | debounceParams = debounced(this.searchQuery, SEARCH_DELAY); |
| 51 | |
| 52 | readonly resultsResource = resource({ |
| 53 | params: () => this.debounceParams.value() || undefined, // coerces empty string to undefined |
| 54 | loader: async ({params}) => this.searchWithQuery(params), |
| 55 | }); |
| 56 | |
| 57 | readonly searchResults = linkedSignal<SearchResultItem[] | undefined, SearchResultItem[]>({ |
| 58 | source: this.resultsResource.value, |
| 59 | computation: (next, prev) => (!next && this.searchQuery() ? prev?.value : next) ?? [], |
| 60 | }); |
| 61 | |
| 62 | readonly emptyState = linkedSignal<{query: string; pending: boolean}, 'start' | 'no-results'>({ |
| 63 | source: () => ({ |
| 64 | query: this.searchQuery(), |
| 65 | pending: |
| 66 | this.searchQuery() !== this.debounceParams.value() || this.resultsResource.isLoading(), |
| 67 | }), |
| 68 | computation: ({query, pending}, prev) => { |
| 69 | if (!query) { |
| 70 | return 'start'; |
| 71 | } |
| 72 | return pending ? (prev?.value ?? 'start') : 'no-results'; |
| 73 | }, |
| 74 | }); |
| 75 | |
| 76 | private getUniqueSearchResultItems(items: SearchResult[]): SearchResult[] { |
| 77 | const uniqueUrls = new Set<string>(); |
| 78 | |
| 79 | return items.filter((item) => { |
| 80 | if (item.type === 'content' && !item._snippetResult.content) { |
| 81 | return false; |
| 82 | } |
| 83 | // Ensure that this result actually matched on the type. |
| 84 | // If not, this is going to be a duplicate. There should be another result in |
| 85 | // the list that already matched on its type. |
| 86 | // A lvl2 match will also return all its lvl3 results as well, even if those |
| 87 | // values don't also match the query. |
| 88 | if ( |
| 89 | item.type.indexOf('lvl') === 0 && |
| 90 | item._snippetResult.hierarchy?.[item.type as 'lvl1']?.matchLevel === 'none' |
| 91 | ) { |
| 92 | return false; |
| 93 | } |
| 94 | |
| 95 | if (item['url'] && typeof item['url'] === 'string' && !uniqueUrls.has(item['url'])) { |
| 96 | uniqueUrls.add(item['url']); |
| 97 | return true; |
| 98 | } |
| 99 | return false; |
| 100 | }); |
| 101 | } |
nothing calls this directly
no test coverage detected