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' },
])
const recorder = useHotkeyRecorder({
onRecord: (hotkey) => {
setShortcuts((prev) =>
prev.map((s) => (s.name === editing ? { ...s, hotkey } : s)),
)
setStatus(`${editing} is now ${hotkey}`)
setEditing(null)
},
onCancel: () => {
setStatus(`${editing} unchanged`)
setEditing(null)
},
onClear: () => {
setShortcuts((prev) =>
prev.map((s) => (s.name === editing ? { ...s, hotkey: null } : s)),
)
setStatus(`${editing} cleared`)
setEditing(null)
},
})
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={() => {
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')
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' },
})
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')
const byTypedKey = useHotkeyRecorder({
recordBy: 'auto',
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
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')
const cancelsOnBlur = useHotkeyRecorder({
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
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')
const tabLeaves = useHotkeyRecorder({
onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
onCancel: () => setStatus('Cancelled'),
})
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>
)
}
const devtoolsPlugins = [hotkeysDevtoolsPlugin()]
render(
<HotkeysProvider>
<App />
<TanStackDevtools plugins={devtoolsPlugins} />
</HotkeysProvider>,
document.getElementById('root')!,
)