Skip to content

Solid Example: CreateHotkeyRecorder

/* @refresh reload */

import { render } from '@solidjs/web'
import { TanStackDevtools } from '@tanstack/solid-devtools'
import {
  HotkeysProvider,
  createFormatForDisplay,
  createHotkey,
  createHotkeyRecorder,
  createHotkeys,
} from '@tanstack/solid-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/solid-hotkeys-devtools'
import { For, Show, createSignal } from 'solid-js'
import type { HotkeyChord } from '@tanstack/solid-hotkeys'
import './index.css'

const devtoolsPlugins = [hotkeysDevtoolsPlugin()]

function ShortcutList() {
  const formatForDisplay = createFormatForDisplay()
  const [status, setStatus] = createSignal('Not recording')
  const [editing, setEditing] = createSignal<string | null>(null)
  const [shortcuts, setShortcuts] = createSignal<
    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.
  // The callbacks read the `editing` signal when they run, so they always
  // see the current row. With the default `maxSteps: 1`, the first chord the
  // user presses ends the recording.
  const recorder = createHotkeyRecorder({
    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 a signal, so mapping them into one
  // `createHotkeys` call is the point here. Pass an accessor so the list
  // re-registers when it changes. 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.
  createHotkeys(() =>
    shortcuts().map((s) => ({
      hotkey: s.hotkey,
      callback: () => setStatus(`Ran ${s.name}`),
      options: { meta: { name: s.name } },
    })),
  )

  return (
    <section class="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 class="shortcut-list">
        <For each={shortcuts()}>
          {(s) => (
            <li>
              <span>{s.name}</span>
              <Show
                when={editing() === s.name && recorder.isRecording()}
                fallback={
                  <Show when={s.hotkey} fallback={<span>No shortcut</span>}>
                    {(hotkey) => <kbd>{formatForDisplay(hotkey())}</kbd>}
                  </Show>
                }
              >
                <span>Press keys</span>
              </Show>
              <Show
                when={editing() === s.name && recorder.isRecording()}
                fallback={
                  <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>
                }
              >
                <button type="button" onClick={recorder.cancelRecording}>
                  Cancel
                </button>
              </Show>
            </li>
          )}
        </For>
      </ul>
      <p role="status" class="status">
        {status()}
      </p>
    </section>
  )
}

function Validation() {
  const formatForDisplay = createFormatForDisplay()
  const [status, setStatus] = createSignal('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 = createHotkeyRecorder({
    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 class="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 class="buttons">
        <button
          type="button"
          onClick={() => {
            recorder.startRecording()
            setStatus('Recording')
          }}
        >
          Record
        </button>
      </div>
      <p role="status" class="status">
        {status()}
      </p>
    </section>
  )
}

function Conflicts() {
  const formatForDisplay = createFormatForDisplay()
  const [status, setStatus] = createSignal('Not recording')

  createHotkey('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 = createHotkeyRecorder({
    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 class="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 class="buttons">
        <button
          type="button"
          onClick={() => {
            recorder.startRecording()
            setStatus('Recording')
          }}
        >
          Record
        </button>
      </div>
      <p role="status" class="status">
        {status()}
      </p>
    </section>
  )
}

function RecordBy() {
  const formatForDisplay = createFormatForDisplay()
  const [status, setStatus] = createSignal('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 = createHotkeyRecorder({
    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 = createHotkeyRecorder({
    recordBy: 'code',
    onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
    onCancel: () => setStatus('Cancelled'),
  })

  return (
    <section class="demo-section">
      <h2>Record by</h2>
      <p>
        Press <kbd>{formatForDisplay('Shift+[Slash]')}</kbd> with each button to
        compare what gets saved.
      </p>
      <div class="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" class="status">
        {status()}
      </p>
    </section>
  )
}

function CancelOnBlur() {
  const [status, setStatus] = createSignal('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 = createHotkeyRecorder({
    onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
    onCancel: () => setStatus('Cancelled'),
  })

  // With `cancelOnBlur: false`, recording waits until the user comes back.
  const keepsRecording = createHotkeyRecorder({
    cancelOnBlur: false,
    onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
    onCancel: () => setStatus('Cancelled'),
  })

  return (
    <section class="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 class="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" class="status">
        {status()}
      </p>
    </section>
  )
}

function RecordTab() {
  const formatForDisplay = createFormatForDisplay()
  const [status, setStatus] = createSignal('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 = createHotkeyRecorder({
    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 = createHotkeyRecorder({
    recordTab: true,
    onRecord: (hotkey) => setStatus(`Recorded ${hotkey}`),
    onCancel: () => setStatus('Cancelled'),
  })

  return (
    <section class="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 class="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" class="status">
        {status()}
      </p>
    </section>
  )
}

function App() {
  return (
    <div class="app">
      <header>
        <h1>Hotkey Recorder</h1>
        <p>
          <code>createHotkeyRecorder</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>

      <TanStackDevtools plugins={devtoolsPlugins} />
    </div>
  )
}

render(
  () => (
    <HotkeysProvider>
      <App />
    </HotkeysProvider>
  ),
  document.getElementById('root')!,
)