Skip to content

Svelte Example: Create Hotkey Recorder

<script lang="ts">
  import {
    createHotkey,
    createHotkeyRecorder,
    createHotkeys,
    getFormatForDisplay,
  } from '@tanstack/svelte-hotkeys'
  import type { HotkeyChord } from '@tanstack/svelte-hotkeys'

  const formatForDisplay = getFormatForDisplay()

  // Shortcut list
  let listStatus = $state('Not recording')
  let editing = $state<string | null>(null)
  let shortcuts = $state<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 `editing` when they run, so they see the row the user
  // clicked last. With the default `maxSteps: 1`, the first chord the user
  // presses ends the recording.
  const recorder = createHotkeyRecorder({
    onRecord: (hotkey) => {
      const row = shortcuts.find((s) => s.name === editing)
      if (row) row.hotkey = hotkey
      listStatus = `${editing} is now ${hotkey}`
      editing = null
    },
    // Escape, `cancelRecording()`, Tab, or the window losing focus. The old
    // shortcut stays.
    onCancel: () => {
      listStatus = `${editing} unchanged`
      editing = null
    },
    // Backspace or Delete. The recorder only reports it; this app decides
    // that clearing unbinds the shortcut.
    onClear: () => {
      const row = shortcuts.find((s) => s.name === editing)
      if (row) row.hotkey = null
      listStatus = `${editing} cleared`
      editing = null
    },
  })

  // The shortcuts are user data held in state, so mapping them into one
  // `createHotkeys` call is the point here. Passed as a function, the list
  // registers again when a shortcut 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: () => (listStatus = `Ran ${s.name}`),
      options: { meta: { name: s.name } },
    })),
  )

  // Validation
  let validationStatus = $state('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 validated = createHotkeyRecorder({
    validate: (_hotkey, { parsedChord }) =>
      parsedChord.modifiers.length > 0 ||
      'Include a modifier, such as Mod or Alt.',
    onReject: ({ reason, message }) =>
      (validationStatus = message
        ? `Rejected: ${message}`
        : `Rejected (${reason})`),
    onRecord: (hotkey) => (validationStatus = `Recorded ${hotkey}`),
    onCancel: () => (validationStatus = 'Cancelled'),
  })

  // Conflicts
  let conflictsStatus = $state('Not recording')

  createHotkey('Mod+K', () => (conflictsStatus = '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 conflictChecked = createHotkeyRecorder({
    detectConflicts: true,
    onReject: ({ reason, hotkey, conflicts }) =>
      (conflictsStatus =
        reason === 'conflict'
          ? `Rejected: ${hotkey} is used by ${conflicts
              ?.map((c) => c.registration.options.meta?.name)
              .join(', ')}`
          : `Rejected (${reason})`),
    onRecord: (hotkey) => (conflictsStatus = `Recorded ${hotkey}`),
    onCancel: () => (conflictsStatus = 'Cancelled'),
  })

  // Record by
  let recordByStatus = $state('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) => (recordByStatus = `Recorded ${hotkey}`),
    onCancel: () => (recordByStatus = '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) => (recordByStatus = `Recorded ${hotkey}`),
    onCancel: () => (recordByStatus = 'Cancelled'),
  })

  // Cancel on blur
  let blurStatus = $state('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) => (blurStatus = `Recorded ${hotkey}`),
    onCancel: () => (blurStatus = 'Cancelled'),
  })

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

  // Record Tab
  let tabStatus = $state('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) => (tabStatus = `Recorded ${hotkey}`),
    onCancel: () => (tabStatus = '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) => (tabStatus = `Recorded ${hotkey}`),
    onCancel: () => (tabStatus = 'Cancelled'),
  })
</script>

<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>
    <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">
        {#each shortcuts as s (s.name)}
          <li>
            <span>{s.name}</span
            >{#if editing === s.name && recorder.isRecording}
              <span>Press keys</span>
            {:else if s.hotkey}
              <kbd>{formatForDisplay(s.hotkey)}</kbd>
            {:else}
              <span>No shortcut</span>
            {/if}{#if editing === s.name && recorder.isRecording}
              <button type="button" onclick={recorder.cancelRecording}>
                Cancel
              </button>
            {:else}
              <button
                type="button"
                onclick={() => {
                  // Starting while already recording does nothing, so a click
                  // on another row moves the recording to that row.
                  recorder.startRecording()
                  editing = s.name
                  listStatus = `Recording ${s.name}`
                }}
              >
                Edit
              </button>
            {/if}
          </li>
        {/each}
      </ul>
      <p role="status" class="status">{listStatus}</p>
    </section>

    <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={() => {
            validated.startRecording()
            validationStatus = 'Recording'
          }}
        >
          Record
        </button>
      </div>
      <p role="status" class="status">{validationStatus}</p>
    </section>

    <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={() => {
            conflictChecked.startRecording()
            conflictsStatus = 'Recording'
          }}
        >
          Record
        </button>
      </div>
      <p role="status" class="status">{conflictsStatus}</p>
    </section>

    <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()
            recordByStatus = 'Recording'
          }}
        >
          Record what it types
        </button>
        <button
          type="button"
          onclick={() => {
            byPosition.startRecording()
            recordByStatus = 'Recording'
          }}
        >
          Record key position
        </button>
      </div>
      <p role="status" class="status">{recordByStatus}</p>
    </section>

    <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()
            blurStatus = 'Recording'
          }}
        >
          Record (default)
        </button>
        <button
          type="button"
          onclick={() => {
            keepsRecording.startRecording()
            blurStatus = 'Recording'
          }}
        >
          Record (cancelOnBlur: false)
        </button>
      </div>
      <p role="status" class="status">{blurStatus}</p>
    </section>

    <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()
            tabStatus = 'Recording'
          }}
        >
          Record (default)
        </button>
        <button
          type="button"
          onclick={() => {
            tabRecords.startRecording()
            tabStatus = 'Recording'
          }}
        >
          Record (recordTab: true)
        </button>
      </div>
      <p role="status" class="status">{tabStatus}</p>
    </section>
  </main>
</div>