import { TanStackDevtools } from '@tanstack/preact-devtools'
import {
HotkeysProvider,
useFormatForDisplay,
useHotkey,
} from '@tanstack/preact-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/preact-hotkeys-devtools'
import { render } from 'preact'
import { useRef, useState } from 'preact/hooks'
import './index.css'
function App() {
const formatForDisplay = useFormatForDisplay()
const [lastBasic, setLastBasic] = useState('none')
useHotkey(
'Mod+S',
(_event, { hotkey, parsedChord }) =>
setLastBasic(
`${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
),
{ meta: { name: 'Save', description: 'Save the document' } },
)
useHotkey('F2', (_event, { hotkey, parsedChord }) =>
setLastBasic(
`${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
),
)
useHotkey('Alt+ArrowUp', (_event, { hotkey, parsedChord }) =>
setLastBasic(
`${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
),
)
useHotkey('Escape', (_event, { hotkey, parsedChord }) =>
setLastBasic(
`${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
),
)
useHotkey(
{ key: 'S', mod: true, shift: true },
(_event, { hotkey, parsedChord }) =>
setLastBasic(
`${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
),
)
const [resetCount, setResetCount] = useState(0)
useHotkey('Mod+K', () => setResetCount((count) => count + 1), {
requireReset: true,
})
const [previewShown, setPreviewShown] = useState(false)
useHotkey('Mod+P', () => setPreviewShown(true))
useHotkey('Mod+P', () => setPreviewShown(false), { eventType: 'keyup' })
const [stateEnabled, setStateEnabled] = useState(true)
const [enabledCounts, setEnabledCounts] = useState({ e: 0, g: 0 })
const getterCheckboxRef = useRef<HTMLInputElement>(null)
useHotkey(
'Mod+E',
() => setEnabledCounts((counts) => ({ ...counts, e: counts.e + 1 })),
{ enabled: stateEnabled },
)
useHotkey(
'Mod+G',
() => setEnabledCounts((counts) => ({ ...counts, g: counts.g + 1 })),
{ enabled: () => getterCheckboxRef.current?.checked ?? false },
)
const [targetCounts, setTargetCounts] = useState({ panel: 0, drawer: 0 })
const panelRef = useRef<HTMLDivElement>(null)
const [drawer, setDrawer] = useState<HTMLDivElement | null>(null)
useHotkey(
'Enter',
() => setTargetCounts((counts) => ({ ...counts, panel: counts.panel + 1 })),
{ target: panelRef },
)
useHotkey(
'Enter',
() =>
setTargetCounts((counts) => ({ ...counts, drawer: counts.drawer + 1 })),
{ target: drawer },
)
const [lastInputs, setLastInputs] = useState('none')
useHotkey('N', (_event, { hotkey }) => setLastInputs(hotkey))
useHotkey('Mod+Enter', (_event, { hotkey }) => setLastInputs(hotkey))
useHotkey('Mod+A', (_event, { hotkey }) => setLastInputs(hotkey), {
ignoreInputs: true,
})
useHotkey('Shift+Enter', (_event, { hotkey }) => setLastInputs(hotkey), {
ignoreInputs: false,
})
const [lastPrevent, setLastPrevent] = useState('none')
const preventInputRef = useRef<HTMLInputElement>(null)
useHotkey('1', (_event, { hotkey }) => setLastPrevent(hotkey), {
target: preventInputRef,
})
useHotkey('2', (_event, { hotkey }) => setLastPrevent(hotkey), {
target: preventInputRef,
preventDefault: false,
})
useHotkey('3', (_event, { hotkey }) => setLastPrevent(hotkey), {
target: preventInputRef,
enabled: false,
preventDefault: 'always',
})
const [stopPanel, setStopPanel] = useState(true)
const [stopCounts, setStopCounts] = useState({ panel: 0, page: 0 })
const stopPanelRef = useRef<HTMLDivElement>(null)
useHotkey(
'Mod+D',
() => setStopCounts((counts) => ({ ...counts, panel: counts.panel + 1 })),
{ target: stopPanelRef, stopPropagation: stopPanel },
)
useHotkey('Mod+D', () =>
setStopCounts((counts) => ({ ...counts, page: counts.page + 1 })),
)
const [captureCounts, setCaptureCounts] = useState({ bubble: 0, capture: 0 })
useHotkey('Mod+ArrowUp', () =>
setCaptureCounts((counts) => ({ ...counts, bubble: counts.bubble + 1 })),
)
useHotkey(
'Mod+ArrowDown',
() =>
setCaptureCounts((counts) => ({
...counts,
capture: counts.capture + 1,
})),
{ capture: true },
)
const [handledCounts, setHandledCounts] = useState({ b: 0, i: 0 })
useHotkey(
'Mod+B',
() => setHandledCounts((counts) => ({ ...counts, b: counts.b + 1 })),
{ ignoreDefaultPrevented: true },
)
useHotkey('Mod+I', () =>
setHandledCounts((counts) => ({ ...counts, i: counts.i + 1 })),
)
const [duplicateCounts, setDuplicateCounts] = useState({ y: 0, u: 0 })
useHotkey(
'Mod+Y',
() => setDuplicateCounts((counts) => ({ ...counts, y: counts.y + 1 })),
{ conflictBehavior: 'allow' },
)
useHotkey(
'Mod+Y',
() => setDuplicateCounts((counts) => ({ ...counts, y: counts.y + 1 })),
{ conflictBehavior: 'allow' },
)
useHotkey('Mod+U', () =>
setDuplicateCounts((counts) => ({ ...counts, u: counts.u + 1 })),
)
useHotkey('Mod+U', () =>
setDuplicateCounts((counts) => ({ ...counts, u: counts.u + 1 })),
)
return (
<div className="app">
<header>
<h1>useHotkey</h1>
<p>
useHotkey registers one hotkey while its component is mounted. Each
section below shows one way to write a hotkey or one of its options.
</p>
</header>
<main>
<section className="demo-section">
<h2>Chords as strings and objects</h2>
<p>
Press <kbd>{formatForDisplay('Mod+S')}</kbd>,{' '}
<kbd>{formatForDisplay('F2')}</kbd>,{' '}
<kbd>{formatForDisplay('Alt+ArrowUp')}</kbd>,{' '}
<kbd>{formatForDisplay('Escape')}</kbd>, or{' '}
<kbd>{formatForDisplay('Mod+Shift+S')}</kbd>. The last one is
written as an object.
</p>
<p role="status" className="info-box">
Last fired: {lastBasic}
</p>
<p className="hint">
For a hotkey per platform or more than one hotkey per action, see
the useHotkey-alternates example. For sequences such as G then H,
see useHotkey-sequences.
</p>
</section>
<section className="demo-section">
<h2>Fire once while held</h2>
<p>
Hold <kbd>{formatForDisplay('Mod+K')}</kbd>. The count goes up once
per press, not on every key repeat.
</p>
<p role="status" className="info-box">
Mod+K: {resetCount}
</p>
</section>
<section className="demo-section">
<h2>Fire on key release</h2>
<p>
Hold <kbd>{formatForDisplay('Mod+P')}</kbd> to show the preview.
Release it to hide the preview.
</p>
<p role="status" className="info-box">
{previewShown ? 'Preview shown' : 'Preview hidden'}
</p>
</section>
<section className="demo-section">
<h2>Turn hotkeys on and off</h2>
<p>
<kbd>{formatForDisplay('Mod+E')}</kbd> reads <code>enabled</code>{' '}
from Preact state. <kbd>{formatForDisplay('Mod+G')}</kbd> reads it
from a function on each key press.
</p>
<label className="control">
<input
type="checkbox"
checked={stateEnabled}
onChange={(event) => setStateEnabled(event.currentTarget.checked)}
/>
Enable Mod+E
</label>
<label className="control">
<input type="checkbox" ref={getterCheckboxRef} defaultChecked />
Enable Mod+G
</label>
<p role="status" className="info-box">
Mod+E: {enabledCounts.e}, Mod+G: {enabledCounts.g}
</p>
</section>
<section className="demo-section">
<h2>Listen on one element</h2>
<p>
Click the panel or the drawer, then press{' '}
<kbd>{formatForDisplay('Enter')}</kbd>. Each has its own hotkey.
</p>
<div className="target-grid">
<div ref={panelRef} tabIndex={0} className="target-area">
Panel
</div>
<Drawer panelRef={setDrawer} />
</div>
<p role="status" className="info-box">
Panel: {targetCounts.panel}, drawer: {targetCounts.drawer}
</p>
</section>
<section className="demo-section">
<h2>Typing in text fields</h2>
<p>
Press <kbd>{formatForDisplay('N')}</kbd>,{' '}
<kbd>{formatForDisplay('Mod+Enter')}</kbd>,{' '}
<kbd>{formatForDisplay('Mod+A')}</kbd>, and{' '}
<kbd>{formatForDisplay('Shift+Enter')}</kbd> on the page, then in
the text field. In the field, N types and Mod+A selects the text.
</p>
<label className="control">
Text field <input type="text" />
</label>
<p role="status" className="info-box">
Last fired: {lastInputs}
</p>
</section>
<section className="demo-section">
<h2>The browser's default action</h2>
<p>
Type 1, 2, and 3 in the field. Only 2 types, because the hotkeys for
1 and 3 call <code>preventDefault</code>. The hotkey for 3 is
disabled, so it doesn't fire.
</p>
<label className="control">
Digits <input type="text" ref={preventInputRef} />
</label>
<p role="status" className="info-box">
Last fired: {lastPrevent}
</p>
</section>
<section className="demo-section">
<h2>Stop outer hotkeys</h2>
<p>
The panel and the page each have a{' '}
<kbd>{formatForDisplay('Mod+D')}</kbd> hotkey. Click the panel and
press it, then turn off stopping and press it again.
</p>
<label className="control">
<input
type="checkbox"
checked={stopPanel}
onChange={(event) => setStopPanel(event.currentTarget.checked)}
/>
Stop propagation in the panel
</label>
<div ref={stopPanelRef} tabIndex={0} className="target-area">
Panel
</div>
<p role="status" className="info-box">
Panel: {stopCounts.panel}, page: {stopCounts.page}
</p>
</section>
<section className="demo-section">
<h2>Run before a widget's own handler</h2>
<p>
Click the widget, which stops every key from reaching the page. Then
press <kbd>{formatForDisplay('Mod+ArrowUp')}</kbd> and{' '}
<kbd>{formatForDisplay('Mod+ArrowDown')}</kbd>. Only the capture
hotkey fires.
</p>
{}
<div
tabIndex={0}
className="target-area"
onKeyDown={(event) => event.stopPropagation()}
>
Widget
</div>
<p role="status" className="info-box">
Bubble: {captureCounts.bubble}, capture: {captureCounts.capture}
</p>
</section>
<section className="demo-section">
<h2>Keys another listener already handled</h2>
<p>
Click the editor and press <kbd>{formatForDisplay('Mod+B')}</kbd>{' '}
and <kbd>{formatForDisplay('Mod+I')}</kbd>. The editor prevents
both, so only Mod+I fires. Outside the editor, both fire.
</p>
{}
<div
tabIndex={0}
className="target-area"
onKeyDown={(event) => {
if (event.ctrlKey || event.metaKey) event.preventDefault()
}}
>
Editor
</div>
<p role="status" className="info-box">
Mod+B: {handledCounts.b}, Mod+I: {handledCounts.i}
</p>
</section>
<section className="demo-section">
<h2>Duplicate hotkeys</h2>
<p>
<kbd>{formatForDisplay('Mod+Y')}</kbd> and{' '}
<kbd>{formatForDisplay('Mod+U')}</kbd> are each registered twice, so
one press runs two callbacks. Mod+U uses the default{' '}
<code>conflictBehavior</code>, so the console shows a warning for it
in development.
</p>
<p role="status" className="info-box">
Mod+Y: {duplicateCounts.y}, Mod+U: {duplicateCounts.u}
</p>
</section>
</main>
</div>
)
}
function Drawer({
panelRef,
}: {
panelRef: (element: HTMLDivElement | null) => void
}) {
const [open, setOpen] = useState(false)
return (
<div>
<button aria-expanded={open} onClick={() => setOpen(!open)}>
Toggle drawer
</button>
{open && (
<div ref={panelRef} tabIndex={0} className="target-area">
Drawer
</div>
)}
</div>
)
}
const devtoolsPlugins = [hotkeysDevtoolsPlugin()]
render(
<HotkeysProvider>
<App />
<TanStackDevtools plugins={devtoolsPlugins} />
</HotkeysProvider>,
document.getElementById('root')!,
)