TanStack

Vue Example: App Hotkeys

<script setup lang="ts">
import { TanStackDevtools } from '@tanstack/vue-devtools'
import {
  useAppHotkeyList,
  useAppHotkeys,
  useCustomHotkeys,
  useFormatForDisplay,
  useHotkey,
  useHotkeyRecorder,
  useHotkeyRegistrations,
} from '@tanstack/vue-hotkeys'
import { HotkeysDevtoolsPanel } from '@tanstack/vue-hotkeys-devtools'
import { computed, ref } from 'vue'
import type { AppHotkeyId } from '@tanstack/vue-hotkeys'

const plugins = [{ name: 'TanStack Hotkeys', component: HotkeysDevtoolsPanel }]

// The effective app hotkeys from the provider in index.ts: each declaration
// with the user's custom hotkey applied.
const appHotkeys = useAppHotkeys()
const formatForDisplay = useFormatForDisplay()

// Register app hotkeys: handlers by id. The getter reads the current hotkey,
// so a registration moves when the user changes it below.
const lastAction = ref('')
useHotkey(
  () => appHotkeys.value['doc.save'],
  () => (lastAction.value = 'Save'),
)
useHotkey(
  () => appHotkeys.value['nav.inbox'],
  () => (lastAction.value = 'Go to inbox'),
)
// Registers nothing while Archive has no hotkey. Once the user assigns one
// below, this starts firing without any change here.
useHotkey(
  () => appHotkeys.value['doc.archive'],
  () => (lastAction.value = 'Archive'),
)

// Enabled getter and call-site meta.
const note = ref('')
const published = ref('')
// The default `ignoreInputs: 'auto'` lets Mod shortcuts fire in text fields,
// so Mod+Enter works while typing in the note. The hotkey calls
// `preventDefault`, so the textarea gets no new line.
useHotkey(
  () => appHotkeys.value['doc.publish'],
  () => (published.value = note.value.trim()),
  {
    // In Vue a getter is a reactive source: the registration updates when
    // `note` changes, and `trigger()` and key presses read the result. A
    // getter that reads the textarea element directly would not update.
    enabled: () => !!note.value.trim(),
    // Merged over the declared meta for this registration only. Registration
    // lists, such as the buttons below, show "Publish note"; the cheat sheet
    // keeps the declared "Publish".
    meta: { name: 'Publish note' },
  },
)

// Run actions without a key press: mounted registrations of app hotkeys. A
// registration's meta includes call-site meta, so Publish shows as
// "Publish note".
const allRegistrations = useHotkeyRegistrations()
const registrations = computed(() =>
  allRegistrations.value.filter((reg) => reg.options.appHotkeyId !== undefined),
)
const result = ref('')

// Cheat sheet: every app hotkey, mounted or not, in declaration order.
const items = useAppHotkeyList()
const groups = computed(() => [
  ...new Set(items.value.map((item) => item.appHotkey.meta?.group)),
])
const customCount = computed(
  () => items.value.filter((item) => item.isCustom).length,
)

// Change hotkeys. The provider saves each change.
const {
  customHotkeys,
  setCustomHotkey,
  resetCustomHotkey,
  resetCustomHotkeys,
  findConflicts,
} = useCustomHotkeys()
const editing = ref<AppHotkeyId | null>(null)
const message = ref('No changes')

const nameOf = (id: AppHotkeyId) =>
  items.value.find((item) => item.appHotkey.id === id)?.appHotkey.meta?.name

// One recorder for every row. `maxSteps: Infinity` records a chord or a
// sequence: press each chord, then Enter. Escape cancels. Backspace with
// nothing recorded clears the hotkey. App hotkeys don't fire while it
// records.
const { steps, isRecording, startRecording } = useHotkeyRecorder({
  maxSteps: Infinity,
  // Rejecting keeps the recording open with its steps.
  validate: (hotkey, context) => {
    if (!editing.value) return false
    // Pass `context` so a hotkey spelled differently that the same key press
    // fires counts as a conflict.
    const conflicts = findConflicts(editing.value, hotkey, context)
    return (
      conflicts.length === 0 ||
      `Not changed: used by ${conflicts[0]?.meta?.name}`
    )
  },
  onReject: (rejection) =>
    (message.value = rejection.message ?? 'Not changed: try another hotkey'),
  onRecord: (hotkey, context) => {
    if (!editing.value) return
    setCustomHotkey(editing.value, hotkey, context)
    message.value = `Changed ${nameOf(editing.value)}`
    editing.value = null
  },
  onClear: () => {
    if (!editing.value) return
    setCustomHotkey(editing.value, null)
    message.value = `Unassigned ${nameOf(editing.value)}`
    editing.value = null
  },
  onCancel: () => {
    message.value = 'Recording cancelled'
    editing.value = null
  },
})
</script>

<template>
  <div class="app">
    <header>
      <h1>App Hotkeys</h1>
      <p>
        Declare every hotkey once with <code>defineAppHotkeys</code>, register
        handlers by id, list them in a cheat sheet, and let users change them.
      </p>
    </header>

    <main>
      <section class="demo-section">
        <h2>Register app hotkeys</h2>
        <p>
          Components register a handler for an app hotkey by its id. The labels
          follow the hotkeys you change below.
        </p>
        <ul>
          <li>
            Save:
            <kbd>{{
              (appHotkeys['doc.save'].hotkey &&
                formatForDisplay(appHotkeys['doc.save'].hotkey)) ||
              'Unassigned'
            }}</kbd>
          </li>
          <li>
            Go to inbox:
            <kbd>{{
              (appHotkeys['nav.inbox'].hotkey &&
                formatForDisplay(appHotkeys['nav.inbox'].hotkey)) ||
              'Unassigned'
            }}</kbd>
          </li>
          <li>
            Archive:
            <kbd>{{
              (appHotkeys['doc.archive'].hotkey &&
                formatForDisplay(appHotkeys['doc.archive'].hotkey)) ||
              'Unassigned'
            }}</kbd>
          </li>
        </ul>
        <p role="status">
          {{ lastAction ? `Last action: ${lastAction}` : 'No action yet' }}
        </p>
      </section>

      <section class="demo-section">
        <h2>Enabled getter and call-site meta</h2>
        <p>
          Type a note, then press
          <kbd>{{
            (appHotkeys['doc.publish'].hotkey &&
              formatForDisplay(appHotkeys['doc.publish'].hotkey)) ||
            'Unassigned'
          }}</kbd
          >. Publish does nothing while the note is empty.
        </p>
        <label>
          Note
          <textarea v-model="note" rows="3" />
        </label>
        <p role="status">
          {{ published ? `Published: ${published}` : 'Nothing published' }}
        </p>
      </section>

      <section class="demo-section">
        <h2>Run actions without a key press</h2>
        <p>
          Each button calls the registration's <code>trigger()</code>, which
          runs its handler and returns whether it ran. It checks only
          <code>enabled</code>.
        </p>
        <div class="toolbar">
          <button
            v-for="reg in registrations"
            :key="reg.id"
            type="button"
            @click="
              result = reg.trigger()
                ? `Ran: ${reg.options.meta?.name}`
                : `Not run: ${reg.options.meta?.name}`
            "
          >
            {{ reg.options.meta?.name }}
          </button>
        </div>
        <p role="status">{{ result || 'No button clicked' }}</p>
      </section>

      <section class="demo-section">
        <h2>Cheat sheet</h2>
        <p>
          Lists every app hotkey, including ones no mounted component registers,
          such as Archive before it has a hotkey.
        </p>
        <div v-for="group in groups" :key="group">
          <h3>{{ group }}</h3>
          <ul>
            <template
              v-for="{ appHotkey, isCustom } in items"
              :key="appHotkey.id"
            >
              <li v-if="appHotkey.meta?.group === group">
                {{ appHotkey.meta?.name }}:
                <kbd>{{
                  (appHotkey.hotkey && formatForDisplay(appHotkey.hotkey)) ||
                  'Unassigned'
                }}</kbd
                >{{ isCustom ? ' (custom)' : '' }}<br /><small>{{
                  appHotkey.meta?.description
                }}</small>
              </li>
            </template>
          </ul>
        </div>
        <p role="status">Customized: {{ customCount }} of {{ items.length }}</p>
      </section>

      <section class="demo-section">
        <h2>Change hotkeys</h2>
        <p>
          Changes are saved to <code>localStorage</code> and survive a reload.
          Only differences from the declared defaults are saved, so users who
          never changed a hotkey get your new defaults.
        </p>
        <table>
          <tbody>
            <tr v-for="{ appHotkey, isCustom } in items" :key="appHotkey.id">
              <th scope="row">{{ appHotkey.meta?.name }}</th>
              <td>
                <kbd>{{
                  editing === appHotkey.id
                    ? formatForDisplay(steps) || 'Press keys'
                    : (appHotkey.hotkey &&
                        formatForDisplay(appHotkey.hotkey)) ||
                      'Unassigned'
                }}</kbd>
              </td>
              <td>
                <button
                  type="button"
                  :disabled="isRecording"
                  @click="
                    () => {
                      editing = appHotkey.id
                      message = `Recording ${appHotkey.meta?.name}: press keys, then Enter`
                      startRecording()
                    }
                  "
                >
                  Change
                </button>
                {{ ' ' }}
                <button
                  type="button"
                  :disabled="isRecording || !isCustom"
                  @click="
                    () => {
                      resetCustomHotkey(appHotkey.id)
                      message = `Reset ${appHotkey.meta?.name}`
                    }
                  "
                >
                  Reset
                </button>
              </td>
            </tr>
          </tbody>
        </table>
        <p>Saved: <code>{{ JSON.stringify(customHotkeys) }}</code></p>
        <button
          type="button"
          :disabled="isRecording"
          @click="
            () => {
              resetCustomHotkeys()
              message = 'Reset all hotkeys'
            }
          "
        >
          Reset all
        </button>
        <p role="status">{{ message }}</p>
      </section>
    </main>

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