|
| 1 | +import { normalizeSearchParam } from '#shared/utils/url' |
| 2 | +import { debounce } from 'perfect-debounce' |
| 3 | + |
| 4 | +// Pages that have their own local filter using ?q |
| 5 | +const pagesWithLocalFilter = new Set(['~username', 'org']) |
| 6 | + |
| 7 | +export function useGlobalSearch() { |
| 8 | + const { searchProvider } = useSearchProvider() |
| 9 | + const searchProviderValue = computed(() => { |
| 10 | + const p = normalizeSearchParam(route.query.p) |
| 11 | + if (p === 'npm' || searchProvider.value === 'npm') return 'npm' |
| 12 | + return 'algolia' |
| 13 | + }) |
| 14 | + const router = useRouter() |
| 15 | + const route = useRoute() |
| 16 | + const searchQuery = useState<string>('search-query', () => { |
| 17 | + if (pagesWithLocalFilter.has(route.name as string)) { |
| 18 | + return '' |
| 19 | + } |
| 20 | + return normalizeSearchParam(route.query.q) |
| 21 | + }) |
| 22 | + |
| 23 | + // clean search input when navigating away from search page |
| 24 | + watch( |
| 25 | + () => route.query.q, |
| 26 | + urlQuery => { |
| 27 | + const value = normalizeSearchParam(urlQuery) |
| 28 | + if (!value) searchQuery.value = '' |
| 29 | + }, |
| 30 | + ) |
| 31 | + const updateUrlQueryImpl = (value: string, provider: 'npm' | 'algolia') => { |
| 32 | + const isSameQuery = route.query.q === value && route.query.p === provider |
| 33 | + // Don't navigate away from pages that use ?q for local filtering |
| 34 | + if (pagesWithLocalFilter.has(route.name as string) || isSameQuery) { |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + if (route.name === 'search') { |
| 39 | + router.replace({ |
| 40 | + query: { |
| 41 | + ...route.query, |
| 42 | + q: value || undefined, |
| 43 | + p: provider === 'npm' ? 'npm' : undefined, |
| 44 | + }, |
| 45 | + }) |
| 46 | + return |
| 47 | + } |
| 48 | + router.push({ |
| 49 | + name: 'search', |
| 50 | + query: { |
| 51 | + q: value, |
| 52 | + p: provider === 'npm' ? 'npm' : undefined, |
| 53 | + }, |
| 54 | + }) |
| 55 | + } |
| 56 | + const updateUrlQuery = debounce(updateUrlQueryImpl, 250) |
| 57 | + |
| 58 | + function flushUpdateUrlQuery() { |
| 59 | + updateUrlQuery.flush() |
| 60 | + } |
| 61 | + |
| 62 | + const searchQueryValue = computed({ |
| 63 | + get: () => searchQuery.value, |
| 64 | + set: async (value: string) => { |
| 65 | + searchQuery.value = value |
| 66 | + |
| 67 | + // Leading debounce implementation as it doesn't work properly out of the box (https://github.com/unjs/perfect-debounce/issues/43) |
| 68 | + if (!updateUrlQuery.isPending()) { |
| 69 | + updateUrlQueryImpl(value, searchProvider.value) |
| 70 | + } |
| 71 | + updateUrlQuery(value, searchProvider.value) |
| 72 | + }, |
| 73 | + }) |
| 74 | + return { model: searchQueryValue, provider: searchProviderValue, flushUpdateUrlQuery } |
| 75 | +} |
0 commit comments