Skip to content

Commit

Permalink
search: Add keyboard navigation to results
Browse files Browse the repository at this point in the history
After searching for a string, the user can navigate results by pressing up/down arrows.
  • Loading branch information
zsol committed May 26, 2024
1 parent 141caae commit c2b7549
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion www/components/core/Search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ const ItemLink = styled(Link)`
display: block;
padding: ${(props) => props.theme.spacing.xs};
text-decoration: none;
&:focus {
background-color: ${(props) => props.theme.colors.input.hover};
}
width: 100%;
`;
Expand Down Expand Up @@ -93,21 +96,39 @@ export const Search = ({ descriptors }: SearchParams) => {
}
}, [searchTerm]);

function keyPressHandler(event: React.KeyboardEvent, index: number) {
if (event.key == "ArrowDown" && index + 1 < (results?.length ?? 0)) {
document.getElementById(`SearchResultItem_Link_${index+1}`)?.focus();
event.preventDefault();
} else if (event.key == "ArrowUp" && index >= 0) {
let target = document.getElementById(index == 0 ? "Search_Input" : `SearchResultItem_Link_${index-1}`);
target?.focus();
event.preventDefault();
}
}

return (
<SearchContainer>
<input
id="Search_Input"
onChange={(event) => {
setSearchTerm(event.target.value);
}}
value={searchTerm}
onKeyDown={(event) => keyPressHandler(event, -1)}
/>
{searchTerm && results && (
<SearchResultContainer>
{results.total === 0 && "No results found"}
{results.total > 0 &&
results.map((result: Result, ind: number) => (
<SearchResultItem key={`${result.obj.name}_${ind}`}>
<ItemLink to={`${result.obj.url}`} onClick={(event) => setSearchTerm("")}>
<ItemLink
id={`SearchResultItem_Link_${ind}`}
to={`${result.obj.url}`}
onClick={(event) => setSearchTerm("")}
onKeyDown={(event) => keyPressHandler(event, ind)}
>
<Match result={result} />
</ItemLink>
</SearchResultItem>
Expand Down

0 comments on commit c2b7549

Please sign in to comment.