Skip to content

Commit c4f5762

Browse files
committed
fix(useGlobalSearch): streamline getFocusedSearchInputValue and improve search query handling
- Moved getFocusedSearchInputValue function to a more appropriate location. - Simplified logic for checking active input element and its type. - Enhanced condition to prevent overwriting search query when focused input matches URL value. - Cleaned up formatting for better readability.
1 parent 432500b commit c4f5762

1 file changed

Lines changed: 11 additions & 15 deletions

File tree

app/composables/useGlobalSearch.ts

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ import { debounce } from 'perfect-debounce'
66
const pagesWithLocalFilter = new Set(['~username', 'org'])
77

88
const SEARCH_DEBOUNCE_MS = 100
9+
const getFocusedSearchInputValue = () => {
10+
if (!import.meta.client) return ''
911

12+
const active = document.activeElement
13+
if (!(active instanceof HTMLInputElement)) return ''
14+
if (active.type !== 'search' && active.name !== 'q') return ''
15+
return active.value
16+
}
1017
export function useGlobalSearch(place: 'header' | 'content' = 'content') {
1118
const { settings } = useSettings()
1219
const { searchProvider } = useSearchProvider()
@@ -18,14 +25,7 @@ export function useGlobalSearch(place: 'header' | 'content' = 'content') {
1825

1926
const router = useRouter()
2027
const route = useRoute()
21-
const getFocusedSearchInputValue = () => {
22-
if (!import.meta.client) return ''
2328

24-
const active = document.activeElement
25-
if (!(active instanceof HTMLInputElement)) return ''
26-
if (active.type !== 'search' && active.name !== 'q') return ''
27-
return active.value
28-
}
2929
// Internally used searchQuery state
3030
const searchQuery = useState<string>('search-query', () => {
3131
// Preserve fast typing before hydration (e.g. homepage autofocus search input).
@@ -62,18 +62,14 @@ export function useGlobalSearch(place: 'header' | 'content' = 'content') {
6262
([routeName, urlQuery]) => {
6363
if (routeName !== 'search') return
6464

65-
// Never clobber in-progress typing while any search input is focused.
65+
const value = normalizeSearchParam(urlQuery)
66+
// Only skip when the focused input already reflects this URL value.
6667
if (import.meta.client) {
67-
const active = document.activeElement
68-
if (
69-
active instanceof HTMLInputElement &&
70-
(active.type === 'search' || active.name === 'q')
71-
) {
68+
const activeValue = getFocusedSearchInputValue()
69+
if (activeValue && activeValue === value) {
7270
return
7371
}
7472
}
75-
76-
const value = normalizeSearchParam(urlQuery)
7773
if (searchQuery.value !== value) {
7874
searchQuery.value = value
7975
}

0 commit comments

Comments
 (0)