Preact Example: UseHeldKeys

import { TanStackDevtools } from '@tanstack/preact-devtools'
import {
  HotkeysProvider,
  useFormatForDisplay,
  useHeldKeyCodes,
  useHeldKeys,
  useHotkey,
  useHotkeyHint,
} from '@tanstack/preact-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/preact-hotkeys-devtools'
import { render } from 'preact'
import { useEffect, useRef, useState } from 'preact/hooks'
import './index.css'

function App() {
  const formatForDisplay = useFormatForDisplay()
  // Held keys in press order, such as ['Shift', 'A']. Updates on every
  // keydown and keyup, and empties when the window loses focus.
  const heldKeys = useHeldKeys()
  // Each held key's physical `event.code`, such as { Shift: 'ShiftLeft' }.
  const heldCodes = useHeldKeyCodes()

  const [history, setHistory] = useState<Array<string>>([])
  const [lastAction, setLastAction] = useState('none')
  const [boldEnabled, setBoldEnabled] = useState(true)

  // Once every key is released, records the most keys held at once, such as
  // 'Shift + Control + A', and keeps the last 10.
  const mostHeld = useRef<Array<string>>([])
  useEffect(() => {
    if (heldKeys.length > mostHeld.current.length) mostHeld.current = heldKeys
    if (heldKeys.length > 0 || mostHeld.current.length === 0) return
    const combination = mostHeld.current.join(' + ')
    mostHeld.current = []
    setHistory((h) => [...h.slice(-9), combination])
  }, [heldKeys])

  // Mod+S would open the browser's Save dialog. A matched hotkey calls
  // `preventDefault` by default, so the page handles it instead.
  useHotkey('Mod+S', () => setLastAction('Save'))
  // While `enabled` is false, Mod+B doesn't fire, and its hint stays hidden.
  useHotkey('Mod+B', () => setLastAction('Bold'), { enabled: boldEnabled })
  useHotkey('Mod+Shift+E', () => setLastAction('Export'))
  useHotkey('Mod+Shift+A', () => setLastAction('Archive'))

  // True while the user holds Mod, and the Mod+S above can fire. The hint
  // registers nothing: it reads the held keys and the registrations.
  const showSaveHint = useHotkeyHint('Mod+S')
  // False while Bold is disabled, even with Mod held, because no enabled
  // registration of Mod+B can fire.
  const showBoldHint = useHotkeyHint('Mod+B')
  // True while the user holds Mod, Shift, or both. Holding a modifier the
  // hotkey doesn't use, such as Alt, hides it.
  const showExportHint = useHotkeyHint('Mod+Shift+E')
  // With `exact: true`, only Mod and Shift held together show the hint.
  // Without it, Mod or Shift alone would show it, as for Export.
  const showArchiveHint = useHotkeyHint('Mod+Shift+A', { exact: true })

  const shownHints = [
    showSaveHint && 'Save',
    showBoldHint && 'Bold',
    showExportHint && 'Export',
    showArchiveHint && 'Archive',
  ].filter(Boolean)

  return (
    <div className="app">
      <header>
        <h1>useHeldKeys</h1>
        <p>
          Track which keys the user is holding, and show a hotkey&apos;s label
          only while its modifiers are held.
        </p>
      </header>

      <main>
        <section className="demo-section">
          <h2>Held keys</h2>
          <p>
            Hold <kbd>Shift</kbd> + <kbd>Control</kbd> + <kbd>A</kbd>, or press
            several letters at once, then release them one by one.
          </p>
          <div className="key-display" aria-hidden="true">
            {heldKeys.map((key) => (
              // `{ key }` formats a raw `event.key` value, such as
              // 'Control' as ⌃ on macOS.
              <kbd key={key} className="large">
                {formatForDisplay({ key })}
              </kbd>
            ))}
          </div>
          <p role="status">
            {heldKeys.length > 0
              ? `Held: ${heldKeys.join(' + ')}`
              : 'No keys held'}
          </p>
        </section>

        <section className="demo-section">
          <h2>Held key codes</h2>
          <p>
            The physical key behind each held key. Left and right{' '}
            <kbd>Shift</kbd> both hold <code>Shift</code>, with different codes.
          </p>
          <p role="status">
            {heldKeys.length > 0
              ? heldKeys.map((key) => `${key}: ${heldCodes[key]}`).join(', ')
              : 'No keys held'}
          </p>
        </section>

        <section className="demo-section">
          <h2>Hotkey hints</h2>
          <p>
            Hold <kbd>{formatForDisplay('Mod')}</kbd>, <kbd>Shift</kbd>, or both
            to see which shortcuts they lead to.
          </p>
          <div className="toolbar">
            <button onClick={() => setLastAction('Save')}>
              Save {showSaveHint && <kbd>{formatForDisplay('Mod+S')}</kbd>}
            </button>
            <button onClick={() => setLastAction('Bold')}>
              Bold {showBoldHint && <kbd>{formatForDisplay('Mod+B')}</kbd>}
            </button>
            <button onClick={() => setLastAction('Export')}>
              Export{' '}
              {showExportHint && <kbd>{formatForDisplay('Mod+Shift+E')}</kbd>}
            </button>
            <button onClick={() => setLastAction('Archive')}>
              Archive{' '}
              {showArchiveHint && <kbd>{formatForDisplay('Mod+Shift+A')}</kbd>}
            </button>
          </div>
          <label>
            <input
              type="checkbox"
              checked={boldEnabled}
              onChange={(e) => setBoldEnabled(e.currentTarget.checked)}
            />{' '}
            Enable Bold
          </label>
          <p>Last action: {lastAction}</p>
          <p role="status">
            {shownHints.length > 0
              ? `Hints shown: ${shownHints.join(', ')}`
              : 'Hints shown: none'}
          </p>
        </section>

        <section className="demo-section">
          <h2>Recent combinations</h2>
          <p>
            Each entry is the most keys you held at once, added when you release
            them all.
          </p>
          <p role="status">
            Recorded {history.length}{' '}
            {history.length === 1 ? 'combination' : 'combinations'}
          </p>
          <ol className="history-list">
            {history.map((combination, i) => (
              <li key={i}>{combination}</li>
            ))}
          </ol>
          <button onClick={() => setHistory([])}>Clear history</button>
        </section>
      </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')!,
)