<script setup lang="ts">
import { TanStackDevtools } from '@tanstack/vue-devtools'
import {
defineHotkey,
findHotkeyConflicts,
normalizeHotkey,
useFormatForDisplay,
useHotkeyRegistrations,
useHotkeys,
validateHotkey,
} from '@tanstack/vue-hotkeys'
import { HotkeysDevtoolsPanel } from '@tanstack/vue-hotkeys-devtools'
import { ref } from 'vue'
import type { Hotkey, HotkeyIssue } from '@tanstack/vue-hotkeys'
const plugins = [{ name: 'TanStack Hotkeys', component: HotkeysDevtoolsPanel }]
const formatForDisplay = useFormatForDisplay()
const counts = ref({ save: 0, undo: 0, redo: 0 })
useHotkeys([
{
hotkey: 'Shift+S',
callback: () => counts.value.save++,
options: { meta: { name: 'Save', description: 'Save the document' } },
},
{
hotkey: 'Shift+U',
callback: () => counts.value.undo++,
options: { meta: { name: 'Undo', description: 'Undo the last action' } },
},
{
hotkey: 'Shift+R',
callback: () => counts.value.redo++,
options: {
meta: { name: 'Redo', description: 'Redo the last undone action' },
},
},
])
const pins = ref({ count: 0, modifiers: '' })
const pin = defineHotkey({
hotkey: 'Shift+P',
callback: (_event, context) => {
pins.value = {
count: pins.value.count + 1,
modifiers: context.parsedChord.modifiers.join('+'),
}
},
options: { requireReset: true, meta: { name: 'Pin' } },
})
useHotkeys([
pin,
{
hotkey: 'Shift+O',
callback: () => (pins.value = { count: 0, modifiers: '' }),
options: { meta: { name: 'Clear pins' } },
},
])
const enabled = ref(true)
const sharedCounts = ref({ a: 0, b: 0, c: 0 })
useHotkeys(
[
{
hotkey: 'Alt+[KeyJ]',
callback: () => sharedCounts.value.a++,
options: { meta: { name: 'Action A' } },
},
{
hotkey: 'Alt+[KeyK]',
callback: () => sharedCounts.value.b++,
options: { meta: { name: 'Action B' } },
},
{
hotkey: 'Alt+[KeyL]',
callback: () => sharedCounts.value.c++,
options: { enabled: true, meta: { name: 'Action C' } },
},
],
{ enabled },
)
const issueText = ({ reason, part }: HotkeyIssue) =>
({
empty: 'Enter a hotkey.',
'empty-part': 'Remove the empty part between + signs.',
'unknown-modifier': `Unknown modifier ${part}.`,
'invalid-physical-key': `${part} isn't a physical key code.`,
'modifier-only': `Add a key after ${part}.`,
'unknown-key': `Unknown key ${part}. Key names are case-sensitive.`,
})[reason]
let nextId = 3
const shortcuts = ref<
Array<{ id: number; hotkey: Hotkey; name: string; count: number }>
>([
{ id: 0, hotkey: 'Shift+A', name: 'Action 1', count: 0 },
{ id: 1, hotkey: 'Shift+B', name: 'Action 2', count: 0 },
{ id: 2, hotkey: 'Shift+C', name: 'Action 3', count: 0 },
])
const newHotkey = ref('')
const newName = ref('')
const message = ref('Add a hotkey to the list.')
useHotkeys(() =>
shortcuts.value.map((s) => ({
hotkey: s.hotkey,
callback: () => s.count++,
options: { meta: { name: s.name } },
})),
)
function addShortcut() {
const name = newName.value.trim()
if (!name) {
message.value = 'Enter a name.'
return
}
const validation = validateHotkey(newHotkey.value.trim())
const issues = [...validation.errors, ...validation.warnings]
if (issues.length > 0) {
message.value = issues.map(issueText).join(' ')
return
}
const hotkey = normalizeHotkey(newHotkey.value.trim())
const [conflict] = findHotkeyConflicts(hotkey)
if (conflict) {
message.value = `Already used by ${conflict.registration.options.meta?.name ?? 'another hotkey'}.`
return
}
shortcuts.value.push({ id: nextId++, hotkey, name, count: 0 })
message.value = `Added ${name}.`
newHotkey.value = ''
newName.value = ''
}
const registrations = useHotkeyRegistrations()
</script>
<template>
<div class="app">
<header>
<h1>useHotkeys</h1>
<p>
Register a list of hotkeys in one useHotkeys call. The list can change
length later, which separate useHotkey calls can't.
</p>
</header>
<main>
<section class="demo-section">
<h2>Register multiple hotkeys</h2>
<div class="hotkey-grid">
<div><kbd>{{ formatForDisplay('Shift+S') }}</kbd> Save</div>
<div><kbd>{{ formatForDisplay('Shift+U') }}</kbd> Undo</div>
<div><kbd>{{ formatForDisplay('Shift+R') }}</kbd> Redo</div>
</div>
<p role="status">
Save: {{ counts.save }}, Undo: {{ counts.undo }}, Redo:
{{ counts.redo }}
</p>
</section>
<section class="demo-section">
<h2>Check one definition with defineHotkey</h2>
<p>
Hold <kbd>{{ formatForDisplay('Shift+P') }}</kbd> to pin once. Press
<kbd>{{ formatForDisplay('Shift+O') }}</kbd> to clear.
</p>
<p role="status">
Pins: {{ pins.count
}}{{ pins.modifiers && `, modifiers: ${pins.modifiers}` }}
</p>
</section>
<section class="demo-section">
<h2>Share options</h2>
<label>
<input v-model="enabled" type="checkbox" />
Enable shared hotkeys
</label>
<div class="hotkey-grid">
<div><kbd>{{ formatForDisplay('Alt+[KeyJ]') }}</kbd> Action A</div>
<div><kbd>{{ formatForDisplay('Alt+[KeyK]') }}</kbd> Action B</div>
<div>
<kbd>{{ formatForDisplay('Alt+[KeyL]') }}</kbd> Action C (always on)
</div>
</div>
<p role="status">
Action A: {{ sharedCounts.a }}, Action B: {{ sharedCounts.b }}, Action
C: {{ sharedCounts.c }}
</p>
</section>
<section class="demo-section">
<h2>Build the list from data</h2>
<ul class="dynamic-list">
<li v-for="s in shortcuts" :key="s.id" class="dynamic-item">
<kbd>{{ formatForDisplay(s.hotkey) }}</kbd>
<span>{{ s.name }}</span>
<span class="count">Fired {{ s.count }}</span>
<button
type="button"
@click="shortcuts = shortcuts.filter((item) => item.id !== s.id)"
>
Remove
</button>
</li>
</ul>
<form class="add-form" @submit.prevent="addShortcut">
<label>
Hotkey
<input v-model="newHotkey" placeholder="Shift+D" />
</label>
<label>
Name
<input v-model="newName" placeholder="Action 4" />
</label>
<button type="submit">Add</button>
</form>
<p role="status">{{ message }}</p>
</section>
<section class="demo-section">
<h2>List the registrations</h2>
<p role="status">{{ registrations.length }} hotkeys registered</p>
<table class="registrations-table">
<thead>
<tr>
<th>Hotkey</th>
<th>Name</th>
<th>Status</th>
<th>Fired</th>
</tr>
</thead>
<tbody>
<tr v-for="reg in registrations" :key="reg.id">
<td>
<kbd>{{ formatForDisplay(reg.hotkey) }}</kbd>
</td>
<td>{{ reg.options.meta?.name }}</td>
<td>{{ reg.status }}</td>
<td>{{ reg.triggerCount }}</td>
</tr>
</tbody>
</table>
</section>
</main>
<TanStackDevtools :plugins="plugins" />
</div>
</template>