TanStack

Vue Example: UseHotkeyRecorder

<script setup lang="ts">
import { TanStackDevtools } from '@tanstack/vue-devtools'
import {
  useFormatForDisplay,
  useHotkey,
  useHotkeyRecorder,
  useHotkeys,
} from '@tanstack/vue-hotkeys'
import { HotkeysDevtoolsPanel } from '@tanstack/vue-hotkeys-devtools'
import { ref } from 'vue'
import type { HotkeyChord } from '@tanstack/vue-hotkeys'

const plugins = [{ name: 'TanStack Hotkeys', component: HotkeysDevtoolsPanel }]
const formatForDisplay = useFormatForDisplay()

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

// The shortcuts are user data held in state, so mapping them into one
// `useHotkeys` call is the point here. The getter makes it register again
// when the list 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.
useHotkeys(() =>
  shortcuts.value.map((s) => ({
    hotkey: s.hotkey,
    callback: () => (listStatus.value = `Ran ${s.name}`),
    options: { meta: { name: s.name } },
  })),
)

function editShortcut(name: string) {
  // Starting while already recording does nothing, so a click on another
  // row moves the recording to that row.
  listRecorder.startRecording()
  editing.value = name
  listStatus.value = `Recording ${name}`
}

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

// Conflicts
const conflictsStatus = ref('Not recording')

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

// Record by
const recordByStatus = ref('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 = useHotkeyRecorder({
  recordBy: 'auto',
  onRecord: (hotkey) => (recordByStatus.value = `Recorded ${hotkey}`),
  onCancel: () => (recordByStatus.value = 'Cancelled'),
})

// Writes the physical key: Shift+/ records `Shift+[Slash]`, which matches
// that key position on every layout, whatever it types.
const byPosition = useHotkeyRecorder({
  recordBy: 'code',
  onRecord: (hotkey) => (recordByStatus.value = `Recorded ${hotkey}`),
  onCancel: () => (recordByStatus.value = 'Cancelled'),
})

// Cancel on blur
const blurStatus = ref('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 = useHotkeyRecorder({
  onRecord: (hotkey) => (blurStatus.value = `Recorded ${hotkey}`),
  onCancel: () => (blurStatus.value = 'Cancelled'),
})

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

// Record Tab
const tabStatus = ref('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 = useHotkeyRecorder({
  onRecord: (hotkey) => (tabStatus.value = `Recorded ${hotkey}`),
  onCancel: () => (tabStatus.value = '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 = useHotkeyRecorder({
  recordTab: true,
  onRecord: (hotkey) => (tabStatus.value = `Recorded ${hotkey}`),
  onCancel: () => (tabStatus.value = 'Cancelled'),
})
</script>

<template>
  <div class="app">
    <header>
      <h1>Hotkey Recorder</h1>
      <p>
        <code>useHotkeyRecorder</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">
          <li v-for="s in shortcuts" :key="s.name">
            <span>{{ s.name }}</span>
            <template
              v-if="editing === s.name && listRecorder.isRecording.value"
            >
              <span>Press keys</span>
              <button @click="listRecorder.cancelRecording()">Cancel</button>
            </template>
            <template v-else>
              <kbd v-if="s.hotkey">{{ formatForDisplay(s.hotkey) }}</kbd>
              <span v-else>No shortcut</span>
              <button @click="editShortcut(s.name)">Edit</button>
            </template>
          </li>
        </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"
            @click="
              validationRecorder.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"
            @click="
              conflictsRecorder.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"
            @click="
              byTypedKey.startRecording();
              recordByStatus = 'Recording'
            "
          >
            Record what it types
          </button>
          <button
            type="button"
            @click="
              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"
            @click="
              cancelsOnBlur.startRecording();
              blurStatus = 'Recording'
            "
          >
            Record (default)
          </button>
          <button
            type="button"
            @click="
              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"
            @click="
              tabLeaves.startRecording();
              tabStatus = 'Recording'
            "
          >
            Record (default)
          </button>
          <button
            type="button"
            @click="
              tabRecords.startRecording();
              tabStatus = 'Recording'
            "
          >
            Record (recordTab: true)
          </button>
        </div>
        <p role="status" class="status">{{ tabStatus }}</p>
      </section>
    </main>

    <TanStackDevtools :plugins="plugins" />
  </div>
</template>