Hotkeys Docs
Examples
Preact Example: UseHotkeyRecorder
import { TanStackDevtools } from '@tanstack/preact-devtools'
import {
HotkeysProvider,
useFormatForDisplay,
useHotkey,
useHotkeyRecorder,
useHotkeys,
} from '@tanstack/preact-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/preact-hotkeys-devtools'
import { render } from 'preact'
import { useState } from 'preact/hooks'
import type { HotkeyChord } from '@tanstack/preact-hotkeys'
import './index.css'
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: HotkeyChord | null }>
>([
{ name: 'Save', hotkey: 'Mod+S' },
{ name: 'Open', hotkey: 'Mod+O' },
{ name: 'Toggle sidebar', hotkey: 'Mod+B' },
])
// One recorder serves every row; `editing` says which row it records for.
// With the default `maxSteps: 1`, the first chord the user presses ends
// the recording.
const recorder = useHotkeyRecorder({
onRecord: (hotkey) => {
setShortcuts((prev) =>
prev.map((s) => (s.name === editing ? { ...s, hotkey } : s)),
)
setStatus(`${editing} is now ${hotkey}`)
setEditing(null)
},
// Escape, `cancelRecording()`, Tab, or the window losing focus. The old
// shortcut stays.
onCancel: () => {
setStatus(`${editing} unchanged`)
setEditing(null)
},
// Backspace or Delete. The recorder only reports it; 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. A null hotkey registers nothing.
// Mod+S and Mod+O would open the browser's Save and Open dialogs; a matched
// hotkey calls `preventDefault` by default. While any recorder is
// recording, these hotkeys pause, so recording Mod+S doesn't also run Save.
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, then press a key combination. Escape cancels and keeps the
old shortcut. Backspace or Delete clears it.
</p>
<ul className="shortcut-list">
{shortcuts.map((s) => (
<li key={s.name}>
<span>{s.name}</span>
{editing === s.name && recorder.isRecording ? (
<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 Validation() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
// Return true to accept, or a message to reject. A rejected chord keeps
// the recorder listening for another one, and `onReject` gets the message.
const recorder = useHotkeyRecorder({
validate: (_hotkey, { parsedChord }) =>
parsedChord.modifiers.length > 0 ||
'Include a modifier, such as Mod or Alt.',
onReject: ({ reason, message }) =>
setStatus(message ? `Rejected: ${message}` : `Rejected (${reason})`),
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Validation</h2>
<p>
This recorder rejects a key without a modifier. Press{' '}
<kbd>{formatForDisplay('K')}</kbd>, then{' '}
<kbd>{formatForDisplay('Mod+Shift+K')}</kbd>.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
recorder.startRecording()
setStatus('Recording')
}}
>
Record
</button>
</div>
<p role="status" className="status">
{status}
</p>
</section>
)
}
function Conflicts() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
useHotkey('Mod+K', () => setStatus('Ran Command palette'), {
meta: { name: 'Command palette' },
})
// `detectConflicts` rejects a chord that a mounted hotkey already uses,
// including the ones in the shortcut list above. Each conflict carries the
// registration, so its `meta.name` can name the owner. Without it, the
// recorder accepts the chord and two hotkeys fire on the same press.
const recorder = useHotkeyRecorder({
detectConflicts: true,
onReject: ({ reason, hotkey, conflicts }) =>
setStatus(
reason === 'conflict'
? `Rejected: ${hotkey} is used by ${conflicts
?.map((c) => c.registration.options.meta?.name)
.join(', ')}`
: `Rejected (${reason})`,
),
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Conflicts</h2>
<p>
This section registers <kbd>{formatForDisplay('Mod+K')}</kbd> for a
command palette. Record it, or <kbd>{formatForDisplay('Mod+S')}</kbd>{' '}
from the list above, to see the conflict. Then record{' '}
<kbd>{formatForDisplay('Mod+J')}</kbd>.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
recorder.startRecording()
setStatus('Recording')
}}
>
Record
</button>
</div>
<p role="status" className="status">
{status}
</p>
</section>
)
}
function RecordBy() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
// The default. Writes what the press typed, the way you'd write the hotkey
// by hand: Shift+/ records `?`, which matches wherever the user's layout
// types `?`. (`recordBy: 'key'` also writes the typed character, even for
// macOS Option+S, which types `ß`.)
const byTypedKey = useHotkeyRecorder({
recordBy: 'auto',
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
// Writes the physical key: Shift+/ records `Shift+[Slash]`, which matches
// that key position on every layout, whatever it types.
const byPosition = useHotkeyRecorder({
recordBy: 'code',
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Record by</h2>
<p>
Press <kbd>{formatForDisplay('Shift+[Slash]')}</kbd> with each button to
compare what gets saved.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
byTypedKey.startRecording()
setStatus('Recording')
}}
>
Record what it types
</button>
<button
type="button"
onClick={() => {
byPosition.startRecording()
setStatus('Recording')
}}
>
Record key position
</button>
</div>
<p role="status" className="status">
{status}
</p>
</section>
)
}
function CancelOnBlur() {
const [status, setStatus] = useState('Not recording')
// By default, recording cancels when the window loses focus, as when the
// user switches apps or tabs. Keys pressed elsewhere never reach the page,
// so the recorder would otherwise wait for a press that isn't coming.
const cancelsOnBlur = useHotkeyRecorder({
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
// With `cancelOnBlur: false`, recording waits until the user comes back.
const keepsRecording = useHotkeyRecorder({
cancelOnBlur: false,
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Cancel on blur</h2>
<p>
Start recording, switch to another app or tab, then come back and press
a key combination.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
cancelsOnBlur.startRecording()
setStatus('Recording')
}}
>
Record (default)
</button>
<button
type="button"
onClick={() => {
keepsRecording.startRecording()
setStatus('Recording')
}}
>
Record (cancelOnBlur: false)
</button>
</div>
<p role="status" className="status">
{status}
</p>
</section>
)
}
function RecordTab() {
const formatForDisplay = useFormatForDisplay()
const [status, setStatus] = useState('Not recording')
// By default, Tab and Shift+Tab cancel recording and move focus as usual,
// so a keyboard user can leave the recorder.
const tabLeaves = useHotkeyRecorder({
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
// With `recordTab: true`, Tab and Shift+Tab are recorded like any other
// chord, and only Escape cancels. Tell users so, as the text below does.
const tabRecords = useHotkeyRecorder({
recordTab: true,
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
return (
<section className="demo-section">
<h2>Record Tab</h2>
<p>
Start recording and press <kbd>{formatForDisplay('Tab')}</kbd> or{' '}
<kbd>{formatForDisplay('Shift+Tab')}</kbd>. With recordTab, press{' '}
<kbd>{formatForDisplay('Escape')}</kbd> to cancel.
</p>
<div className="buttons">
<button
type="button"
onClick={() => {
tabLeaves.startRecording()
setStatus('Recording')
}}
>
Record (default)
</button>
<button
type="button"
onClick={() => {
tabRecords.startRecording()
setStatus('Recording')
}}
>
Record (recordTab: true)
</button>
</div>
<p role="status" className="status">
{status}
</p>
</section>
)
}
function App() {
return (
<div className="app">
<header>
<h1>Hotkey Recorder</h1>
<p>
<code>useHotkeyRecorder</code> records the next key combination the
user presses. Each section shows one recorder option.
</p>
</header>
<main>
<ShortcutList />
<Validation />
<Conflicts />
<RecordBy />
<CancelOnBlur />
<RecordTab />
</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')!,
)