MyKindlebox/mykindlebox/client/src/lib/keyboardNav.js

29 lines
1006 B
JavaScript

// Arrow-key roving focus for the `<ul><li><button>` search-results list used
// by both PedigreeTree's AncestorSlot and RabbitAutocomplete — they render
// the same search-dropdown shape, so the keyboard behavior is shared here
// rather than duplicated. Enter/click activation is native <button> behavior
// and needs no extra handling.
export function handleSearchInputKeyDown(e, { containerEl, close }) {
if (e.key === 'ArrowDown') {
e.preventDefault()
containerEl?.querySelector('ul button')?.focus()
} else if (e.key === 'Escape') {
close()
}
}
export function handleResultKeyDown(e, { containerEl, index, inputEl, close }) {
const buttons = Array.from(containerEl?.querySelectorAll('ul button') ?? [])
if (e.key === 'ArrowDown') {
e.preventDefault()
buttons[index + 1]?.focus()
} else if (e.key === 'ArrowUp') {
e.preventDefault()
if (index === 0) inputEl?.focus()
else buttons[index - 1]?.focus()
} else if (e.key === 'Escape') {
close()
}
}