diff --git a/materialious/src/lib/Search.svelte b/materialious/src/lib/Search.svelte index 8bb50b24..d281164e 100644 --- a/materialious/src/lib/Search.svelte +++ b/materialious/src/lib/Search.svelte @@ -9,9 +9,10 @@ let search: string; let suggestionsForSearch: string[] = []; + let selectedSuggestionIndex: number = -1; let debounceTimer: NodeJS.Timeout; - const debouncedSearch = (event: any) => { + function debouncedSearch(event: any) { if (!searchSuggestions) return; if (debounceTimer) clearTimeout(debounceTimer); @@ -22,11 +23,28 @@ } suggestionsForSearch = (await getSearchSuggestions(event.target.value)).suggestions; }, 250); - }; + } function handleSubmit() { + selectedSuggestionIndex = -1; goto(`/search/${encodeURIComponent(search)}`); } + + function handleKeyDown(event: KeyboardEvent) { + if (event.key === 'ArrowUp') { + event.preventDefault(); + selectedSuggestionIndex = Math.max(selectedSuggestionIndex - 1, -1); + } else if (event.key === 'ArrowDown') { + event.preventDefault(); + selectedSuggestionIndex = Math.min( + selectedSuggestionIndex + 1, + suggestionsForSearch.length - 1 + ); + } else if (event.key === 'Enter' && selectedSuggestionIndex !== -1) { + search = suggestionsForSearch[selectedSuggestionIndex]; + handleSubmit(); + } + }