triplex
triplex copied to clipboard
Keyboard navigation in Open menu
Currently, using Cmd + O to open the Open menu works, and it auto-focuses on the filter input, but it is not easily possible to navigate and select an item. You have to either click, or use Tab to move the focus to the item and press enter. It would be nice to automatically highlight the first item, and pressing Enter confirms it. The user could also use up and down arrows to navigate through the options and press Enter to select the highlighted item. See https://webgamer.io/ for an example (press Cmd + K to open search)
Here is a piece of code I have been using on various projects to move the browsers focus programatically:
// From https://gist.github.com/pl12133/186ec3b599aba9a541e1ab4dafc9d593
// const isInert = node =>
// node.offsetHeight <= 0 || /hidden/.test(getComputedStyle(node).getPropertyValue('visibility'))
export const focusNext = e => {
// Selector lifted from `jkup/focusable.git`
const focusable = Array.from(
document.querySelectorAll(
// 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable], audio[controls], video[controls]'
'a, input, select, textarea, button, [tabindex="0"]'
)
),
step = e && e.shiftKey ? -1 : 1,
activeIndex = focusable.indexOf(document.activeElement),
nextActiveIndex = activeIndex + step,
nextActive = focusable[nextActiveIndex]
// Skip inert elements.
// while (nextActive && isInert(nextActive)) {
// nextActive = focusable[(nextActiveIndex += step)]
// }
if (nextActive) {
// @ts-ignore
nextActive.focus()
e && e.preventDefault?.()
} else {
// @ts-ignore
document.activeElement.blur()
}
}
export const focusPrevious = e => {
// Selector lifted from `jkup/focusable.git`
const focusable = Array.from(
document.querySelectorAll(
// 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable], audio[controls], video[controls]'
'a, input, select, textarea, button, [tabindex="0"]'
)
),
step = e && e.shiftKey ? -1 : 1,
activeIndex = focusable.indexOf(document.activeElement),
nextActiveIndex = activeIndex - step,
nextActive = focusable[nextActiveIndex]
// Skip inert elements.
// while (nextActive && isInert(nextActive)) {
// nextActive = focusable[(nextActiveIndex += step)]
// }
if (nextActive) {
// @ts-ignore
nextActive.focus()
e && e.preventDefault?.()
} else {
// @ts-ignore
document.activeElement.blur()
}
}
You can then do something like this to catch up and down arrows:
const handleKeyDown = e => {
if (e.keyCode === 40) {
e.preventDefault()
focusNext(e)
} else if (e.keyCode === 38) {
e.preventDefault()
focusPrevious(e)
}
}
Good shout, would you be keen to contribute it to the editor?