import { TanStackDevtools } from '@tanstack/preact-devtools'
import {
HotkeysProvider,
defineAppHotkeys,
useAppHotkeyList,
useAppHotkeys,
useCustomHotkeys,
useFormatForDisplay,
useHotkey,
useHotkeyRecorder,
useHotkeyRegistrations,
} from '@tanstack/preact-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/preact-hotkeys-devtools'
import { render } from 'preact'
import { useRef, useState } from 'preact/hooks'
import type { AppHotkeyId } from '@tanstack/preact-hotkeys'
import './index.css'
const navigationHotkeys = defineAppHotkeys({
'nav.inbox': {
hotkey: ['G', 'I'],
meta: {
name: 'Go to inbox',
description: 'Press G, then I',
group: 'Navigation',
},
options: { timeout: 1500 },
},
})
const appHotkeys = defineAppHotkeys({
'doc.save': {
hotkey: 'Mod+S',
meta: { name: 'Save', description: 'Saves the note', group: 'Document' },
options: { requireReset: true },
},
'doc.publish': {
hotkey: 'Mod+Enter',
meta: {
name: 'Publish',
description: 'Works only while the note has text',
group: 'Document',
},
},
'doc.archive': {
hotkey: null,
meta: {
name: 'Archive',
description: 'No default hotkey',
group: 'Document',
},
},
...navigationHotkeys,
})
declare module '@tanstack/preact-hotkeys' {
interface Register {
appHotkeys: typeof appHotkeys
}
}
function Actions() {
const appHotkeys = useAppHotkeys()
const formatForDisplay = useFormatForDisplay()
const [lastAction, setLastAction] = useState('')
useHotkey(appHotkeys['doc.save'], () => setLastAction('Save'))
useHotkey(appHotkeys['nav.inbox'], () => setLastAction('Go to inbox'))
useHotkey(appHotkeys['doc.archive'], () => setLastAction('Archive'))
return (
<section className="demo-section">
<h2>Register app hotkeys</h2>
<p>
Components register a handler for an app hotkey by its id. The labels
follow the hotkeys you change below.
</p>
<ul>
<li>
Save:{' '}
<kbd>
{(appHotkeys['doc.save'].hotkey &&
formatForDisplay(appHotkeys['doc.save'].hotkey)) ||
'Unassigned'}
</kbd>
</li>
<li>
Go to inbox:{' '}
<kbd>
{(appHotkeys['nav.inbox'].hotkey &&
formatForDisplay(appHotkeys['nav.inbox'].hotkey)) ||
'Unassigned'}
</kbd>
</li>
<li>
Archive:{' '}
<kbd>
{(appHotkeys['doc.archive'].hotkey &&
formatForDisplay(appHotkeys['doc.archive'].hotkey)) ||
'Unassigned'}
</kbd>
</li>
</ul>
<p role="status">
{lastAction ? `Last action: ${lastAction}` : 'No action yet'}
</p>
</section>
)
}
function Publisher() {
const appHotkeys = useAppHotkeys()
const formatForDisplay = useFormatForDisplay()
const noteRef = useRef<HTMLTextAreaElement>(null)
const [published, setPublished] = useState('')
useHotkey(
appHotkeys['doc.publish'],
() => setPublished(noteRef.current?.value.trim() ?? ''),
{
enabled: () => !!noteRef.current?.value.trim(),
meta: { name: 'Publish note' },
},
)
return (
<section className="demo-section">
<h2>Enabled getter and call-site meta</h2>
<p>
Type a note, then press{' '}
<kbd>
{(appHotkeys['doc.publish'].hotkey &&
formatForDisplay(appHotkeys['doc.publish'].hotkey)) ||
'Unassigned'}
</kbd>
. Publish does nothing while the note is empty.
</p>
<label>
Note
<textarea ref={noteRef} rows={3} />
</label>
<p role="status">
{published ? `Published: ${published}` : 'Nothing published'}
</p>
</section>
)
}
function Toolbar() {
const [result, setResult] = useState('')
const registrations = useHotkeyRegistrations().filter(
(reg) => reg.options.appHotkeyId !== undefined,
)
return (
<section className="demo-section">
<h2>Run actions without a key press</h2>
<p>
Each button calls the registration's <code>trigger()</code>, which runs
its handler and returns whether it ran. It checks only{' '}
<code>enabled</code>.
</p>
<div className="toolbar">
{registrations.map((reg) => (
<button
key={reg.id}
type="button"
onClick={() => {
const name = reg.options.meta?.name
setResult(reg.trigger() ? `Ran: ${name}` : `Not run: ${name}`)
}}
>
{reg.options.meta?.name}
</button>
))}
</div>
<p role="status">{result || 'No button clicked'}</p>
</section>
)
}
function CheatSheet() {
const formatForDisplay = useFormatForDisplay()
const items = useAppHotkeyList()
const groups = [...new Set(items.map((item) => item.appHotkey.meta?.group))]
const customCount = items.filter((item) => item.isCustom).length
return (
<section className="demo-section">
<h2>Cheat sheet</h2>
<p>
Lists every app hotkey, including ones no mounted component registers,
such as Archive before it has a hotkey.
</p>
{groups.map((group) => (
<div key={group}>
<h3>{group}</h3>
<ul>
{items
.filter((item) => item.appHotkey.meta?.group === group)
.map(({ appHotkey, isCustom }) => (
<li key={appHotkey.id}>
{appHotkey.meta?.name}:{' '}
<kbd>
{(appHotkey.hotkey && formatForDisplay(appHotkey.hotkey)) ||
'Unassigned'}
</kbd>
{isCustom && ' (custom)'}
<br />
<small>{appHotkey.meta?.description}</small>
</li>
))}
</ul>
</div>
))}
<p role="status">
Customized: {customCount} of {items.length}
</p>
</section>
)
}
function Settings() {
const formatForDisplay = useFormatForDisplay()
const items = useAppHotkeyList()
const {
customHotkeys,
setCustomHotkey,
resetCustomHotkey,
resetCustomHotkeys,
findConflicts,
} = useCustomHotkeys()
const [editing, setEditing] = useState<AppHotkeyId | null>(null)
const [message, setMessage] = useState('No changes')
const nameOf = (id: AppHotkeyId) =>
items.find((item) => item.appHotkey.id === id)?.appHotkey.meta?.name
const recorder = useHotkeyRecorder({
maxSteps: Infinity,
validate: (hotkey, context) => {
if (!editing) return false
const conflicts = findConflicts(editing, hotkey, context)
return (
conflicts.length === 0 ||
`Not changed: used by ${conflicts[0]?.meta?.name}`
)
},
onReject: (rejection) =>
setMessage(rejection.message ?? 'Not changed: try another hotkey'),
onRecord: (hotkey, context) => {
if (!editing) return
setCustomHotkey(editing, hotkey, context)
setMessage(`Changed ${nameOf(editing)}`)
setEditing(null)
},
onClear: () => {
if (!editing) return
setCustomHotkey(editing, null)
setMessage(`Unassigned ${nameOf(editing)}`)
setEditing(null)
},
onCancel: () => {
setMessage('Recording cancelled')
setEditing(null)
},
})
return (
<section className="demo-section">
<h2>Change hotkeys</h2>
<p>
Changes are saved to <code>localStorage</code> and survive a reload.
Only differences from the declared defaults are saved, so users who
never changed a hotkey get your new defaults.
</p>
<table>
<tbody>
{items.map(({ appHotkey, isCustom }) => (
<tr key={appHotkey.id}>
<th scope="row">{appHotkey.meta?.name}</th>
<td>
<kbd>
{editing === appHotkey.id
? formatForDisplay(recorder.steps) || 'Press keys'
: (appHotkey.hotkey &&
formatForDisplay(appHotkey.hotkey)) ||
'Unassigned'}
</kbd>
</td>
<td>
<button
type="button"
disabled={recorder.isRecording}
onClick={() => {
setEditing(appHotkey.id)
setMessage(
`Recording ${appHotkey.meta?.name}: press keys, then Enter`,
)
recorder.startRecording()
}}
>
Change
</button>{' '}
<button
type="button"
disabled={recorder.isRecording || !isCustom}
onClick={() => {
resetCustomHotkey(appHotkey.id)
setMessage(`Reset ${appHotkey.meta?.name}`)
}}
>
Reset
</button>
</td>
</tr>
))}
</tbody>
</table>
<p>
Saved: <code>{JSON.stringify(customHotkeys)}</code>
</p>
<button
type="button"
disabled={recorder.isRecording}
onClick={() => {
resetCustomHotkeys()
setMessage('Reset all hotkeys')
}}
>
Reset all
</button>
<p role="status">{message}</p>
</section>
)
}
function App() {
return (
<div className="app">
<header>
<h1>App Hotkeys</h1>
<p>
Declare every hotkey once with <code>defineAppHotkeys</code>, register
handlers by id, list them in a cheat sheet, and let users change them.
</p>
</header>
<main>
<Actions />
<Publisher />
<Toolbar />
<CheatSheet />
<Settings />
</main>
</div>
)
}
const devtoolsPlugins = [hotkeysDevtoolsPlugin()]
render(
<HotkeysProvider
appHotkeys={appHotkeys}
customHotkeys={JSON.parse(
localStorage.getItem('tanstack-hotkeys-app-hotkeys') ?? '{}',
)}
onCustomHotkeysChange={(customHotkeys) =>
localStorage.setItem(
'tanstack-hotkeys-app-hotkeys',
JSON.stringify(customHotkeys),
)
}
>
<App />
<TanStackDevtools plugins={devtoolsPlugins} />
</HotkeysProvider>,
document.getElementById('root')!,
)