Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

search: Add keyboard navigation to results #167

Merged
merged 2 commits into from
May 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 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,13 +96,28 @@ 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();
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about looping around on the results when one reaches the last element in the dropdown and presses Down?


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,8 +126,10 @@ 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>
Expand Down
Loading