Rewrite GlobalEvents.vue to a composable.
I'm rewriting a GlobalEvents.vue
component as a useKeyboardShortcut
composable. The reason is there is no $listeners
in vue 3 (#1547 (closed)) anymore.
It's been used to handle keyboard events in places where the component was used.
Proposed API:
type KeyFilter = string | string[]
export default (key: KeyFilter, handler: () => unknown, prevent = false) => {
-
key
- a key combination (see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) -
handler
- a function to call when the key combination is pressed -
prevent
- preventskeydown
event
The keypresses are registered only when <body>
is an active element, so shift+f pressed twice will input F
into the search box. (First keystroke focuses <input>
and second is not handled as the active element is now <input>
).
When key array is supplied, the keystrokes are handled in strict order, so shift+f is not f+shift
The shortcut is active as long as the component lives or is stopped manually. When component is unmounted, the shortcut listener automatically stops.
Usage:
useKeyboardShortcut('left', () => seek(-5))
useKeyboardShortcut(['shift', 'left'], () => seek(-30), true) // prevent selecting text
const stop = useKeyboardShortcut('up', () => {
console.log('You can\'t invoke me second time!')
stop() // listen only for one keypress
})