Hotkeys Docs
Examples
Preact Example: UseHotkeyRecorder Sequences
import { TanStackDevtools } from '@tanstack/preact-devtools'
import {
HotkeysProvider,
useFormatForDisplay,
useHotkeyRecorder,
useHotkeys,
} from '@tanstack/preact-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/preact-hotkeys-devtools'
import { render } from 'preact'
import { useState } from 'preact/hooks'
import type { Hotkey } from '@tanstack/preact-hotkeys'
import './index.css'
// A recorded hotkey as text: `Mod+S` for a chord, `G H` for a sequence. A
// sequence is an array of chords, such as `['G', 'H']`.
function hotkeyText(hotkey: Hotkey) {
return Array.isArray(hotkey) ? hotkey.join(' ') : hotkey
}
function ShortcutList() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
const [editing, setEditing] = useState<string | null>(null)
const [shortcuts, setShortcuts] = useState<
Array<{ name: string; hotkey: Hotkey | null }>
>([
{ name: 'Save', hotkey: 'Mod+S' },
{ name: 'Go to inbox', hotkey: ['G', 'I'] },
{ name: 'Go to settings', hotkey: ['G', 'S'] },
])
// With `maxSteps: Infinity`, each chord adds a step and Enter saves. One
// step saves as a chord string such as 'Mod+S'; two or more save as a
// sequence such as ['G', 'H']. Backspace removes the last step, and on an
// empty recording calls `onClear`. Escape cancels.
const recorder = useHotkeyRecorder({
maxSteps: Infinity,
onRecord: (hotkey) => {
setShortcuts((prev) =>
prev.map((s) => (s.name === editing ? { ...s, hotkey } : s)),
)
setStatus(`${editing} is now ${hotkeyText(hotkey)}`)
setEditing(null)
},
onCancel: () => {
setStatus(`${editing} unchanged`)
setEditing(null)
},
// The recorder only reports the clear; this app decides that clearing
// unbinds the shortcut.
onClear: () => {
setShortcuts((prev) =>
prev.map((s) => (s.name === editing ? { ...s, hotkey: null } : s)),
)
setStatus(`${editing} cleared`)
setEditing(null)
},
})
// The shortcuts are user data held in state, so mapping them into one
// `useHotkeys` call is the point here. Chords and sequences register the
// same way, and a null hotkey registers nothing. Mod+S would open the
// browser's Save dialog; a matched hotkey calls `preventDefault` by
// default. While any recorder is recording, these hotkeys pause.
useHotkeys(
shortcuts.map((s) => ({
hotkey: s.hotkey,
callback: () => setStatus(`Ran ${s.name}`),
options: { meta: { name: s.name } },
})),
)
return (
<section className="demo-section">
<h2>Shortcut list</h2>
<p>
Click Edit, press each chord in order, then press Enter. Backspace
removes the last chord, or clears the shortcut when none are left.
Escape cancels.
</p>
<ul className="shortcut-list">
{shortcuts.map((s) => (
<li key={s.name}>
<span>{s.name}</span>
{editing === s.name && recorder.isRecording ? (
recorder.steps.length > 0 ? (
<kbd>{formatForDisplay(recorder.steps)}</kbd>
) : (
<span>Press keys</span>
)
) : s.hotkey ? (
<kbd>{formatForDisplay(s.hotkey)}</kbd>
) : (
<span>No shortcut</span>
)}
{editing === s.name && recorder.isRecording ? (
<button type="button" onClick={recorder.cancelRecording}>
Cancel
</button>
) : (
<button
type="button"
onClick={() => {
// Starting while already recording does nothing, so a click
// on another row moves the recording to that row.
recorder.startRecording()
setEditing(s.name)
setStatus(`Recording ${s.name}`)
}}
>
Edit
</button>
)}
</li>
))}
</ul>
<p role="status" className="status">
{status}
</p>
</section>
)
}
function MaxSteps() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
// Recording saves by itself when it reaches `maxSteps`, here the second
// chord. Enter still saves a single chord before that.
const recorder = useHotkeyRecorder({
maxSteps: 2,
onRecord: (hotkey) => setStatus(`Recorded ${hotkeyText(hotkey)}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Max steps</h2>
<p>
Press <kbd>{formatForDisplay('G')}</kbd>, then{' '}
<kbd>{formatForDisplay('H')}</kbd>. Recording ends at the second chord
without Enter.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
recorder.startRecording()
setStatus('Recording')
}}
>
Record
</button>
</div>
<p role="status" className="status">
{status}
</p>
</section>
)
}
function CommitKeys() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
// The default, `commitKeys: 'enter'`: plain Enter saves the steps.
const enterSaves = useHotkeyRecorder({
maxSteps: Infinity,
commitKeys: 'enter',
onRecord: (hotkey) => setStatus(`Recorded ${hotkeyText(hotkey)}`),
onCancel: () => setStatus('Cancelled'),
})
// With `commitKeys: 'none'`, Enter is recorded as a step, so a sequence
// can end in Enter. Save with `commitRecording()`, `idleTimeoutMs`, or
// `maxSteps` instead.
const enterRecords = useHotkeyRecorder({
maxSteps: Infinity,
commitKeys: 'none',
onRecord: (hotkey) => setStatus(`Recorded ${hotkeyText(hotkey)}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Commit keys</h2>
<p>
Press <kbd>{formatForDisplay('G')}</kbd>, then{' '}
<kbd>{formatForDisplay('Enter')}</kbd> with each button. With
commitKeys: 'none', click Done to save.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
enterSaves.startRecording()
setStatus('Recording')
}}
>
Record (commitKeys: 'enter')
</button>
<button
type="button"
onClick={() => {
enterRecords.startRecording()
setStatus('Recording')
}}
>
Record (commitKeys: 'none')
</button>
<button
type="button"
disabled={enterRecords.steps.length === 0}
onClick={enterRecords.commitRecording}
>
Done
</button>
</div>
{enterRecords.steps.length > 0 && (
<p>
Steps: <kbd>{formatForDisplay(enterRecords.steps)}</kbd>
</p>
)}
<p role="status" className="status">
{status}
</p>
</section>
)
}
function IdleTimeout() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
// Saves one second after the last chord, so the user doesn't need Enter.
// Each new chord restarts the wait. Without it, a recording waits for
// Enter or `maxSteps`.
const recorder = useHotkeyRecorder({
maxSteps: Infinity,
idleTimeoutMs: 1000,
onRecord: (hotkey) => setStatus(`Recorded ${hotkeyText(hotkey)}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Idle timeout</h2>
<p>
Press <kbd>{formatForDisplay('G')}</kbd>, then{' '}
<kbd>{formatForDisplay('H')}</kbd>, and wait one second.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
recorder.startRecording()
setStatus('Recording')
}}
>
Record
</button>
</div>
{recorder.steps.length > 0 && (
<p>
Steps: <kbd>{formatForDisplay(recorder.steps)}</kbd>
</p>
)}
<p role="status" className="status">
{status}
</p>
</section>
)
}
function Validation() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
// `validate` runs when the recording saves. Check `context.kind` before
// reading `parsedChord` (one step) or `parsedSequence` (two or more). A
// rejected recording keeps its steps, so the user can add a chord or press
// Backspace instead of starting over.
const recorder = useHotkeyRecorder({
maxSteps: Infinity,
validate: (_hotkey, context) =>
context.kind === 'sequence' ||
context.parsedChord.modifiers.length > 0 ||
'A single chord needs a modifier.',
onReject: ({ reason, message }) =>
setStatus(message ? `Rejected: ${message}` : `Rejected (${reason})`),
onRecord: (hotkey) => setStatus(`Recorded ${hotkeyText(hotkey)}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Validation</h2>
<p>
Press <kbd>{formatForDisplay('G')}</kbd>, then{' '}
<kbd>{formatForDisplay('Enter')}</kbd> to see the rejection. Then press{' '}
<kbd>{formatForDisplay('H')}</kbd> and{' '}
<kbd>{formatForDisplay('Enter')}</kbd>.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
recorder.startRecording()
setStatus('Recording')
}}
>
Record
</button>
</div>
{recorder.steps.length > 0 && (
<p>
Steps: <kbd>{formatForDisplay(recorder.steps)}</kbd>
</p>
)}
<p role="status" className="status">
{status}
</p>
</section>
)
}
function Conflicts() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
// `detectConflicts` rejects a recording that a mounted hotkey already
// uses, including prefixes: a chord conflicts with a sequence that starts
// with it, so `G` conflicts with G I. A sequence conflicts with a chord
// equal to its first step. G H and G I don't conflict.
const recorder = useHotkeyRecorder({
maxSteps: Infinity,
detectConflicts: true,
onReject: ({ reason, hotkey, conflicts }) =>
setStatus(
reason === 'conflict' && hotkey
? `Rejected: ${hotkeyText(hotkey)} is used by ${conflicts
?.map((c) => c.registration.options.meta?.name)
.join(', ')}`
: `Rejected (${reason})`,
),
onRecord: (hotkey) => setStatus(`Recorded ${hotkeyText(hotkey)}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Conflicts</h2>
<p>
Record <kbd>{formatForDisplay('G')}</kbd> alone, or{' '}
<kbd>{formatForDisplay(['G', 'I'])}</kbd>, to conflict with the list
above. Then record <kbd>{formatForDisplay(['G', 'H'])}</kbd>.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
recorder.startRecording()
setStatus('Recording')
}}
>
Record
</button>
</div>
{recorder.steps.length > 0 && (
<p>
Steps: <kbd>{formatForDisplay(recorder.steps)}</kbd>
</p>
)}
<p role="status" className="status">
{status}
</p>
</section>
)
}
function App() {
return (
<div className="app">
<header>
<h1>Recording Sequences</h1>
<p>
With <code>maxSteps</code> above 1, <code>useHotkeyRecorder</code>{' '}
records several chords in a row, such as G then I. Each section shows
one recorder option.
</p>
</header>
<main>
<ShortcutList />
<MaxSteps />
<CommitKeys />
<IdleTimeout />
<Validation />
<Conflicts />
</main>
</div>
)
}
// TanStackDevtools as sibling of App to avoid Preact hook errors when hotkeys update state
const devtoolsPlugins = [hotkeysDevtoolsPlugin()]
render(
<HotkeysProvider>
<App />
<TanStackDevtools plugins={devtoolsPlugins} />
</HotkeysProvider>,
document.getElementById('root')!,
)