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 27, 2024
1 parent 99fa363 commit ea87fbc
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions 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,13 +96,26 @@ 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) {
const 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>
Expand All @@ -108,9 +124,11 @@ export const Search = ({ descriptors }: SearchParams) => {
results.map((result: Result, ind: number) => (
<SearchResultItem key={`${result.obj.name}_${ind}`}>
<ItemLink
id={`SearchResultItem_Link_${ind}`}
to={`${result.obj.url}`}
onClick={(event) => setSearchTerm("")}
>
onClick={() => setSearchTerm("")}
onKeyDown={(event) => keyPressHandler(event, ind)}
>
<Match result={result} />
</ItemLink>
</SearchResultItem>
Expand Down

0 comments on commit ea87fbc

Please sign in to comment.