forma-36
forma-36 copied to clipboard
💡 Proposal - useKeyboard hook in f36-utils
Discussed in https://github.com/contentful/forma-36/discussions/1008
Originally posted by mshaaban0 March 18, 2021
The problem
I see in our code base we have many approaches devs takes to listen to keyboard events and detect keycode, ..etc.
const handleKeyUp = (e: React.KeyboardEvent) => {
if (KeyCodes.esc(e)) {
hidePanel();
}
};
document.addEventListener('keyup', (handleKeyUp as unknown) as EventListener);
return () => document.removeEventListener('keyup', (handleKeyUp as unknown) as EventListener);
That I believe we can make simpler, and since it's considered as interactions, I believe it would fit well in F36
The proposed solution
A simple hook that accepts a reference or a document, adds/remove the events on mount and unmount, and finally emits callback functions
Also maybe some predefined ones for what we think is the most keyboard buttons we need to listen to?
const { onEsc, onEnter, onKey } = useKeyboard(ref | document);
onEsc(() => alert('👹'))
onKey('h', () => alert('hello'))
Common A11y Keyboard interactions
See full list https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/Grid_Role#keyboard_interactions
Key | Action |
---|---|
→ | Moves focus to the right. |
← | Moves focus to the left. |
↓ | Moves focus down. |
↑ | Moves focus up. |
Page Down | Moves focus down an author-determined number of rows. |
Page Up | Moves focus up an author-determined number of rows. |
Home | Moves focus to the first cell in the row that contains focus. |
End | Moves focus to the last cell in the row that contains focus. |
ctrl + Home | Moves focus to the first cell in the first row. |
ctrl + End | Moves focus to the last cell in the last row. |
Or
Key combination | Action |
---|---|
ctrl + Space | Select the column that contains the focus. |
shift + Space | Selects the row that contains the focus. |
ctrl + A | Selects all cells. |
shift + → | Extends selection one cell to the right. |
shift + ← | Extends selection one cell to the left. |
shift + ↓ | Extends selection one cell down. |
shift + ↑ | Extends selection one cell up. |
Marking issue as stale since there was no acitivty for 30 days
Closing this as done: https://f36.contentful.com/utils/use-keyboard 😁