Skip to content

Vue Example: Kitchen Sink

<script setup lang="ts">
import { TanStackDevtools } from '@tanstack/vue-devtools'
import {
  HotkeysProvider,
  useFormatForAria,
  useFormatForDisplay,
  useHeldKeyCodes,
  useHeldKeys,
  useHotkey,
  useHotkeyRegistrations,
  useHotkeys,
  useKeyHold,
} from '@tanstack/vue-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/vue-hotkeys-devtools'
import { computed, inject, onUnmounted, provide, ref } from 'vue'
import Editor from './Editor.vue'
import Formatting from './Formatting.vue'
import Hint from './Hint.vue'
import Recording from './Recording.vue'
import Sequences from './Sequences.vue'
import Tickets from './Tickets.vue'
import type { Ref } from 'vue'

const formatForDisplay = useFormatForDisplay()
const formatForAria = useFormatForAria()
// Provided by index.ts, which passes it to the root provider.
const characterKeys = inject<Ref<boolean>>('characterKeys', ref(true))

const pages = [
  { path: '/', name: 'Tickets', component: Tickets, hotkey: 'Alt+[Digit1]' },
  {
    path: '/editor',
    name: 'Editor',
    component: Editor,
    hotkey: 'Alt+[Digit2]',
  },
  {
    path: '/sequences',
    name: 'Sequences',
    component: Sequences,
    hotkey: 'Alt+[Digit3]',
  },
  {
    path: '/recording',
    name: 'Recording',
    component: Recording,
    hotkey: 'Alt+[Digit4]',
  },
  {
    path: '/formatting',
    name: 'Formatting',
    component: Formatting,
    hotkey: 'Alt+[Digit5]',
  },
] as const
const path = ref(location.hash.slice(1) || '/')
const update = () => {
  path.value = location.hash.slice(1) || '/'
}
window.addEventListener('hashchange', update)
onUnmounted(() => window.removeEventListener('hashchange', update))
const page = computed(
  () => pages.find((p) => p.path === path.value) ?? pages[0],
)
const activity = ref<Array<string>>([])
provide('log', (message: string) => {
  activity.value = [message, ...activity.value].slice(0, 6)
})
const show = ref(false)
const keys = useHeldKeys(),
  codes = useHeldKeyCodes(),
  shift = useKeyHold('Shift')
const registrations = useHotkeyRegistrations()
const groups = computed(() => [
  ...new Set(
    registrations.value.map((reg) => reg.options.meta?.group ?? 'Other'),
  ),
])
useHotkeys(
  pages.map((p) => ({
    hotkey: p.hotkey,
    callback: () => {
      location.hash = p.path
    },
    options: { meta: { name: `Open ${p.name}`, group: 'Navigation' } },
  })),
  { ignoreInputs: true },
)
useHotkey(
  'Alt+Shift+[KeyK]',
  () => {
    show.value = !show.value
  },
  { meta: { name: 'Show shortcuts', group: 'Navigation' } },
)
</script>
<template>
  <header>
    <h1>TanStack Hotkeys kitchen sink</h1>
    <p>
      Hold Alt / Option to see shortcut hints. Change routes to see
      registrations mount and unmount.
    </p>
    <nav aria-label="Examples">
      <a
        v-for="p in pages"
        :key="p.path"
        :href="`#${p.path}`"
        :class="{ active: path === p.path }"
        :aria-keyshortcuts="formatForAria(p.hotkey)"
        >{{ p.name }} <Hint :hotkey="p.hotkey"
      /></a>
    </nav>
    <button
      @click="show = !show"
      :aria-expanded="show"
      :aria-keyshortcuts="formatForAria('Alt+Shift+[KeyK]')"
    >
      {{ show ? 'Hide' : 'Show' }} shortcuts
      <Hint hotkey="Alt+Shift+[KeyK]" />
    </button>
    <label>
      <input type="checkbox" v-model="characterKeys" />
      Single-key shortcuts
    </label>
    <small>
      Turn off to suspend shortcuts made only of keys that type a character,
      such as the G G sequence (WCAG 2.1.4).
    </small>
  </header>
  <section v-if="show" aria-label="Registered shortcuts">
    <h2>Registered shortcuts</h2>
    <p>
      Global and current-route registrations, including disabled handlers. Each
      page renders a <code>HotkeysProvider</code> with its own scope. Target
      shortcuts run only while focus is inside their target.
    </p>
    <div v-for="group in groups" :key="group">
      <h3>{{ group }}</h3>
      <table>
        <thead>
          <tr>
            <th>Action</th>
            <th>Binding</th>
            <th>Scope</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="reg in registrations.filter(
              (reg) => (reg.options.meta?.group ?? 'Other') === group,
            )"
            :key="reg.id"
          >
            <td>
              {{ reg.options.meta?.name ?? reg.id }}<br /><small>{{
                reg.options.meta?.description
              }}</small>
            </td>
            <td>
              {{ formatForDisplay(reg.hotkey, { sequenceSeparator: ' → ' }) }}
            </td>
            <td>{{ reg.options.scope }}</td>
            <td>
              {{
                reg.options.enabled === false
                  ? 'Disabled'
                  : `${reg.triggerCount} fired`
              }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </section>
  <main>
    <!-- Each page gets its own hotkey scope, active while it is mounted. -->
    <HotkeysProvider :key="page.path" :scope="page.name.toLowerCase()">
      <component :is="page.component" />
    </HotkeysProvider>
  </main>
  <section>
    <h2>Key state</h2>
    <p>
      Keys: {{ keys.join(' + ') || 'None' }}<br />Codes:
      {{ Object.values(codes).join(' + ') || 'None' }}<br />Shift:
      {{ shift ? 'held' : 'released' }}
    </p>
    <h2>Activity</h2>
    <button @click="activity = []">Clear log</button>
    <ul aria-live="polite">
      <li v-for="(message, i) in activity" :key="i">{{ message }}</li>
    </ul>
  </section>
  <TanStackDevtools :plugins="[hotkeysDevtoolsPlugin()]" />
</template>