useShortcuts
Usage
Give useShortcuts an object: on the left the shortcut, on the right what to do.
<script setup lang="ts">
const isSearchOpen = ref(false)
useShortcuts({
'mod+k': () => {
isSearchOpen.value = true
},
})
</script>
Here, pressing ⌘ K on a Mac, or Ctrl K on Windows, opens the search.
The shortcuts work as long as the component is on the page, and stop on their own when it goes away. With the Nuxt module, useShortcuts is auto-imported. In a Vue app, import it from @kuina-ui/vue.
Writing shortcuts
One key
Write the key on its own.
useShortcuts({
'?': () => openHelp(),
'n': () => createTransaction(),
})
A key with a modifier
Join the modifier and the key with +.
useShortcuts({
'mod+s': () => saveDraft(),
'shift+enter': () => addLine(),
'ctrl+alt+n': () => createAccount(),
})
| Modifier | On a Mac | On Windows and Linux |
|---|---|---|
mod | ⌘ | Ctrl |
ctrl | Ctrl | Ctrl |
meta | ⌘ | ⊞ |
alt | ⌥ | Alt |
shift | Shift | Shift |
Prefer mod for app shortcuts: one shortcut gives each user the key they expect.
Keys one after the other
Separate the keys with a space. The user has one second between each key.
useShortcuts({
'g d': () => goToDashboard(),
'g t': () => goToTransactions(),
})
Here, G then D opens the dashboard.
Special keys
Write their name in lowercase.
useShortcuts({
'escape': () => closePanel(),
'arrowdown': () => selectNextRow(),
'mod+enter': () => sendPayment(),
})
Available names: escape, enter, tab, space, backspace, delete, insert, arrowup, arrowdown, arrowleft, arrowright, home, end, pageup, pagedown, plus, and f1 to f24.
Shortcut options
Instead of a function, give an object to change how a shortcut behaves. The function then goes in handler.
Run it inside a field
By default, a shortcut does nothing while the user types in a field, so typing N in a form writes the letter. Set allowInEditable to true for shortcuts that are useful in fields.
useShortcuts({
escape: {
handler: () => clearSearch(),
allowInEditable: true,
},
})
Keep what the browser does
By default, a shortcut replaces what the browser would do with the same keys, like saving the page on Ctrl S. Set preventDefault to false to let the browser act too.
useShortcuts({
'mod+p': {
handler: () => trackPrint(),
preventDefault: false,
},
})
Know which shortcut was pressed
The function receives the keyboard event, then the shortcut that matched.
useShortcuts({
'g d': (keyboardEvent, { shortcut }) => {
console.log(shortcut)
},
})
Listening options
A second object, optional, sets when and where the shortcuts listen.
Only under a condition
enabled turns the shortcuts on and off. Here, Escape closes the panel only while it is open.
const isPanelOpen = ref(false)
useShortcuts({ escape: () => closePanel() }, { enabled: isPanelOpen })
Only inside an element
target limits the shortcuts to an element: they run only when the focus is inside it.
<script setup lang="ts">
const transactionList = useTemplateRef('transactionList')
useShortcuts({ arrowdown: () => selectNextRow() }, { target: transactionList })
</script>
<template>
<ul ref="transactionList" tabindex="0">
<li>…</li>
</ul>
</template>
With your own rule
guards adds rules of your own. A rule returns true to let the shortcut run. Here, the shortcuts stop while a dialog is open.
const isDialogOpen = ref(false)
useShortcuts({ n: () => createTransaction() }, { guards: [() => !isDialogOpen.value] })
Shortcuts that change
Give a function instead of an object, and the shortcuts follow the state of the page.
const isEditing = ref(false)
useShortcuts(() =>
isEditing.value
? { 'escape': () => cancelEditing(), 'mod+enter': () => saveChanges() }
: { e: () => startEditing() },
)
Here, E starts editing, then Esc cancels and ⌘ Enter saves.
From menu items
Pass the items of a Menu to extractMenuShortcuts to make their shortcuts work.
import { extractMenuShortcuts, type MenuEntry } from '@kuina-ui/vue'
const transactionItems: MenuEntry[] = [
{ label: 'Edit', shortcut: 'mod+e', onSelect: () => openTransactionEditor() },
{ label: 'Duplicate', shortcut: 'mod+d', onSelect: () => duplicateTransaction() },
]
useShortcuts(extractMenuShortcuts(transactionItems))
Good to know
- Exact modifiers:
mod+kdoes not run on ⌘ Shift K. Writemod+shift+kfor that one. - Symbols:
?runs whatever keys the keyboard needs to type it, and@works with AltGr. - Keyboard layouts: shortcuts follow the letter printed on the key, so
mod+aworks on AZERTY and QWERTY keyboards alike. - Upper or lower case:
Escapeandescapeare the same shortcut. - Typos: a shortcut like
ctlr+kthrows an error as soon as the component appears, instead of silently never running.
API
useShortcuts(shortcuts, listeningOptions?)
Shortcut options
| Option | Type | Default |
|---|---|---|
handler | (keyboardEvent, { shortcut }) => void | |
allowInEditable | boolean | false |
preventDefault | boolean | true |
Listening options
| Option | Type | Default |
|---|---|---|
enabled | boolean, ref or getter | true |
target | element, ref or getter | document |
guards | Array<(keyboardEvent, shortcutBinding) => boolean> | [] |