Skip to content

Commit 92e4588

Browse files
committed
perf: fix leading debounce in search
1 parent 1cd2348 commit 92e4588

File tree

1 file changed

+28
-25
lines changed

1 file changed

+28
-25
lines changed

app/composables/useGlobalSearch.ts

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -28,44 +28,47 @@ export function useGlobalSearch() {
2828
if (!value) searchQuery.value = ''
2929
},
3030
)
31-
const updateUrlQuery = debounce(
32-
(value: string, provider: 'npm' | 'algolia') => {
33-
// Don't navigate away from pages that use ?q for local filtering
34-
if (pagesWithLocalFilter.has(route.name as string)) {
35-
return
36-
}
37-
if (route.name === 'search') {
38-
router.replace({
39-
query: {
40-
...route.query,
41-
q: value || undefined,
42-
p: provider === 'npm' ? 'npm' : undefined,
43-
},
44-
})
45-
return
46-
}
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+
}
4737

48-
router.push({
49-
name: 'search',
38+
if (route.name === 'search') {
39+
router.replace({
5040
query: {
51-
q: value,
41+
...route.query,
42+
q: value || undefined,
5243
p: provider === 'npm' ? 'npm' : undefined,
5344
},
5445
})
55-
},
56-
250,
57-
{ leading: true },
58-
)
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)
5957

6058
function flushUpdateUrlQuery() {
6159
updateUrlQuery.flush()
6260
}
6361

6462
const searchQueryValue = computed({
6563
get: () => searchQuery.value,
66-
set: (value: string) => {
67-
updateUrlQuery(value, searchProvider.value)
64+
set: async (value: string) => {
6865
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)
6972
},
7073
})
7174
return { model: searchQueryValue, provider: searchProviderValue, flushUpdateUrlQuery }

0 commit comments

Comments
 (0)