Skip to content

Vue Example: UseHeldKeys

<script setup lang="ts">
import { TanStackDevtools } from '@tanstack/vue-devtools'
import {
  useFormatForDisplay,
  useHeldKeyCodes,
  useHeldKeys,
  useHotkey,
  useHotkeyHint,
} from '@tanstack/vue-hotkeys'
import { HotkeysDevtoolsPanel } from '@tanstack/vue-hotkeys-devtools'
import { computed, ref, watch } from 'vue'

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

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 = ref<Array<string>>([])
const lastAction = ref('none')
const boldEnabled = ref(true)

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

// 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', () => (lastAction.value = 'Save'))
// While `enabled` is false, Mod+B doesn't fire, and its hint stays hidden.
useHotkey('Mod+B', () => (lastAction.value = 'Bold'), { enabled: boldEnabled })
useHotkey('Mod+Shift+E', () => (lastAction.value = 'Export'))
useHotkey('Mod+Shift+A', () => (lastAction.value = '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 = computed(() =>
  [
    showSaveHint.value && 'Save',
    showBoldHint.value && 'Bold',
    showExportHint.value && 'Export',
    showArchiveHint.value && 'Archive',
  ].filter(Boolean),
)
</script>

<template>
  <div class="app">
    <header>
      <h1>useHeldKeys</h1>
      <p>
        Track which keys the user is holding, and show a hotkey's label only
        while its modifiers are held.
      </p>
    </header>

    <main>
      <section class="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 class="key-display" aria-hidden="true">
          <!-- `{ key }` formats a raw `event.key` value, such as 'Control' as
               ⌃ on macOS. -->
          <kbd v-for="key in heldKeys" :key="key" class="large">
            {{ formatForDisplay({ key }) }}
          </kbd>
        </div>
        <p role="status">
          {{
            heldKeys.length > 0
              ? `Held: ${heldKeys.join(' + ')}`
              : 'No keys held'
          }}
        </p>
      </section>

      <section class="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 class="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 class="toolbar">
          <button @click="lastAction = 'Save'">
            Save <kbd v-if="showSaveHint">{{ formatForDisplay('Mod+S') }}</kbd>
          </button>
          <button @click="lastAction = 'Bold'">
            Bold <kbd v-if="showBoldHint">{{ formatForDisplay('Mod+B') }}</kbd>
          </button>
          <button @click="lastAction = 'Export'">
            Export
            <kbd v-if="showExportHint">{{
              formatForDisplay('Mod+Shift+E')
            }}</kbd>
          </button>
          <button @click="lastAction = 'Archive'">
            Archive
            <kbd v-if="showArchiveHint">{{
              formatForDisplay('Mod+Shift+A')
            }}</kbd>
          </button>
        </div>
        <label>
          <input v-model="boldEnabled" type="checkbox" />
          Enable Bold
        </label>
        <p>Last action: {{ lastAction }}</p>
        <p role="status">
          {{
            shownHints.length > 0
              ? `Hints shown: ${shownHints.join(', ')}`
              : 'Hints shown: none'
          }}
        </p>
      </section>

      <section class="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 class="history-list">
          <li v-for="(combination, i) in history" :key="i">
            {{ combination }}
          </li>
        </ol>
        <button @click="history = []">Clear history</button>
      </section>
    </main>

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