afcapel / stimulus-autocomplete

Stimulus autocomplete component
MIT License
478 stars 61 forks source link

Use keyboard navigation to navigate results #103

Closed netshade closed 2 years ago

netshade commented 2 years ago

Currently, the input element captures blur and closes the results when focus leaves the element. It seems like it would be desirable in cases where someone is using a screenreader or keyboard navigation that, if focus leaves the textbox but is transferred to one of the elements in the result list, that list of results will remain open until focus has entirely transitioned out of the autocomplete results.

If my interpretation is correct here, I'm happy to do the work for a PR.

netshade commented 2 years ago

( I should note that I see in the code where there are hooks to respond to keyboard events, but they also don't appear to work for me in Safari 15.3 or Chrome 99.0.4844.51, Mac OS 12.2.1 )

afcapel commented 2 years ago

@netshade thanks for offering some help. The autocomplete accessibility is something I want to improve.

Technically the autocomplete is an aria combo box. According to the spec, the popup with the results should not be in the keyboard tab sequence.

Keyboard Interaction

  • Tab: The textbox is in the page Tab sequence.
    • Note: The popup indicator icon or button (if present), the popup, and the popup descendants are excluded from the page Tab sequence.

https://www.w3.org/TR/wai-aria-practices-1.1/#keyboard-interaction-6

The autocomplete already implements the rest of the keyboard interactions. However, it'd be nice if we could automatically set the aria combobox role in the autocomplete and add aria listbox role to the results.

afcapel commented 2 years ago

( I should note that I see in the code where there are hooks to respond to keyboard events, but they also don't appear to work for me in Safari 15.3 or Chrome 99.0.4844.51, Mac OS 12.2.1 )

You can add new event key handlers (or override existing ones) adding onXKeydown event handlers to your subclass. For example, to do something when the "a" key is pressed:

import { Autocomplete } from "stimulus-autocomplete"

export default class extends Autocomplete {
  onaKeydown = (event) => {
    console.log("a key down")
  }
}
netshade commented 2 years ago

Ah, thank you - I didn't realize the Aria autocomplete behavior was all arrow key based. That combined w/ .active not applying any actual visual changes by default made it seem like things simply weren't working.

Thanks for telling me about the aria behavior, I was assuming that tabindex and tabbing between results was the correct way to specify behavior. Issue no longer valid.