Skip to content

Commit

Permalink
feat: command bar up down navigation (#7546)
Browse files Browse the repository at this point in the history
  • Loading branch information
daveleek authored Jul 5, 2024
1 parent 2e205fc commit 2f94834
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions frontend/src/component/commandBar/CommandBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,53 @@ export const CommandBar = () => {
});
const placeholder = `Command bar (${hotkey})`;

const findCommandBarLinksAndSelectedIndex = () => {
const allCommandBarLinks =
searchContainerRef.current?.querySelectorAll('ul > a');
if (!allCommandBarLinks || allCommandBarLinks.length === 0) return;

let selectedIndex = -1;

allCommandBarLinks.forEach((link, index) => {
if (link === document.activeElement) {
selectedIndex = index;
}
});

return { allCommandBarLinks, selectedIndex };
};

useKeyboardShortcut({ key: 'ArrowDown', preventDefault: true }, () => {
const itemsAndIndex = findCommandBarLinksAndSelectedIndex();
if (!itemsAndIndex) return;
const { allCommandBarLinks, selectedIndex } = itemsAndIndex;

const newIndex = selectedIndex + 1;
if (newIndex >= allCommandBarLinks.length) return;

(allCommandBarLinks[newIndex] as HTMLElement).focus();
});
useKeyboardShortcut({ key: 'ArrowUp', preventDefault: true }, () => {
const itemsAndIndex = findCommandBarLinksAndSelectedIndex();
if (!itemsAndIndex) return;
const { allCommandBarLinks, selectedIndex } = itemsAndIndex;

const newIndex = selectedIndex - 1;

if (newIndex >= 0) {
(allCommandBarLinks[newIndex] as HTMLElement).focus();
} else {
const element = searchInputRef.current;
if (element) {
element.focus();
element.setSelectionRange(
element.value.length,
element.value.length,
);
}
}
});

useOnClickOutside([searchContainerRef], hideSuggestions);
const onKeyDown = (event: React.KeyboardEvent) => {
if (event.key === 'Escape') {
Expand Down

0 comments on commit 2f94834

Please sign in to comment.