<script module lang="ts">
import { defineAppHotkeys } from '@tanstack/svelte-hotkeys'
const navigationHotkeys = defineAppHotkeys({
'nav.inbox': {
hotkey: ['G', 'I'],
meta: {
name: 'Go to inbox',
description: 'Press G, then I',
group: 'Navigation',
},
options: { timeout: 1500 },
},
})
const appHotkeys = defineAppHotkeys({
'doc.save': {
hotkey: 'Mod+S',
meta: { name: 'Save', description: 'Saves the note', group: 'Document' },
options: { requireReset: true },
},
'doc.publish': {
hotkey: 'Mod+Enter',
meta: {
name: 'Publish',
description: 'Works only while the note has text',
group: 'Document',
},
},
'doc.archive': {
hotkey: null,
meta: {
name: 'Archive',
description: 'No default hotkey',
group: 'Document',
},
},
...navigationHotkeys,
})
declare module '@tanstack/svelte-hotkeys' {
interface Register {
appHotkeys: typeof appHotkeys
}
}
</script>
<script lang="ts">
import { TanStackDevtools } from '@tanstack/svelte-devtools'
import {
createHotkey,
createHotkeyRecorder,
getAppHotkeyList,
getAppHotkeys,
getCustomHotkeys,
getFormatForDisplay,
getHotkeyRegistrations,
setHotkeysContext,
} from '@tanstack/svelte-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/svelte-hotkeys-devtools'
import type { AppHotkeyId } from '@tanstack/svelte-hotkeys'
setHotkeysContext({
appHotkeys,
customHotkeys: JSON.parse(
localStorage.getItem('tanstack-hotkeys-app-hotkeys') ?? '{}',
),
onCustomHotkeysChange: (customHotkeys) =>
localStorage.setItem(
'tanstack-hotkeys-app-hotkeys',
JSON.stringify(customHotkeys),
),
})
const formatForDisplay = getFormatForDisplay()
const effective = getAppHotkeys()
let lastAction = $state('')
createHotkey(
() => effective.current['doc.save'],
() => (lastAction = 'Save'),
)
createHotkey(
() => effective.current['nav.inbox'],
() => (lastAction = 'Go to inbox'),
)
createHotkey(
() => effective.current['doc.archive'],
() => (lastAction = 'Archive'),
)
let note = $state<HTMLTextAreaElement>()
let published = $state('')
createHotkey(
() => effective.current['doc.publish'],
() => (published = note?.value.trim() ?? ''),
{
enabled: () => !!note?.value.trim(),
meta: { name: 'Publish note' },
},
)
const registrations = getHotkeyRegistrations()
let result = $state('')
const list = getAppHotkeyList()
const groups = $derived([
...new Set(list.current.map((item) => item.appHotkey.meta?.group)),
])
const customCount = $derived(
list.current.filter((item) => item.isCustom).length,
)
const custom = getCustomHotkeys()
let editing = $state<AppHotkeyId | null>(null)
let message = $state('No changes')
const nameOf = (id: AppHotkeyId) =>
list.current.find((item) => item.appHotkey.id === id)?.appHotkey.meta?.name
const recorder = createHotkeyRecorder({
maxSteps: Infinity,
validate: (hotkey, context) => {
if (!editing) return false
const conflicts = custom.findConflicts(editing, hotkey, context)
return (
conflicts.length === 0 ||
`Not changed: used by ${conflicts[0]?.meta?.name}`
)
},
onReject: (rejection) =>
(message = rejection.message ?? 'Not changed: try another hotkey'),
onRecord: (hotkey, context) => {
if (!editing) return
custom.setCustomHotkey(editing, hotkey, context)
message = `Changed ${nameOf(editing)}`
editing = null
},
onClear: () => {
if (!editing) return
custom.setCustomHotkey(editing, null)
message = `Unassigned ${nameOf(editing)}`
editing = null
},
onCancel: () => {
message = 'Recording cancelled'
editing = null
},
})
const devtoolsPlugins = [hotkeysDevtoolsPlugin()]
</script>
<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
>{(effective.current['doc.save'].hotkey &&
formatForDisplay(effective.current['doc.save'].hotkey)) ||
'Unassigned'}</kbd
>
</li>
<li>
Go to inbox: <kbd
>{(effective.current['nav.inbox'].hotkey &&
formatForDisplay(effective.current['nav.inbox'].hotkey)) ||
'Unassigned'}</kbd
>
</li>
<li>
Archive: <kbd
>{(effective.current['doc.archive'].hotkey &&
formatForDisplay(effective.current['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
>{(effective.current['doc.publish'].hotkey &&
formatForDisplay(effective.current['doc.publish'].hotkey)) ||
'Unassigned'}</kbd
>. Publish does nothing while the note is empty.
</p>
<label>
Note
<textarea bind:this={note} rows="3"></textarea>
</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">
{#each registrations.hotkeys.filter((reg) => reg.options.appHotkeyId !== undefined) as reg (reg.id)}
<button
type="button"
onclick={() => {
const name = reg.options.meta?.name
result = reg.trigger() ? `Ran: ${name}` : `Not run: ${name}`
}}
>
{reg.options.meta?.name}
</button>
{/each}
</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>
{#each groups as group (group)}
<div>
<h3>{group}</h3>
<ul>
{#each list.current.filter((item) => item.appHotkey.meta?.group === group) as { appHotkey, isCustom } (appHotkey.id)}
<li>
{appHotkey.meta?.name}:
<kbd
>{(appHotkey.hotkey && formatForDisplay(appHotkey.hotkey)) ||
'Unassigned'}</kbd
>{isCustom ? ' (custom)' : ''}<br /><small
>{appHotkey.meta?.description}</small
>
</li>
{/each}
</ul>
</div>
{/each}
<p role="status">
Customized: {customCount} of {list.current.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>
{#each list.current as { appHotkey, isCustom } (appHotkey.id)}
<tr>
<th scope="row">{appHotkey.meta?.name}</th>
<td>
<kbd
>{editing === appHotkey.id
? formatForDisplay(recorder.steps) || 'Press keys'
: (appHotkey.hotkey &&
formatForDisplay(appHotkey.hotkey)) ||
'Unassigned'}</kbd
>
</td>
<td>
<button
type="button"
disabled={recorder.isRecording}
onclick={() => {
editing = appHotkey.id
message = `Recording ${appHotkey.meta?.name}: press keys, then Enter`
recorder.startRecording()
}}
>
Change
</button>
<button
type="button"
disabled={recorder.isRecording || !isCustom}
onclick={() => {
custom.resetCustomHotkey(appHotkey.id)
message = `Reset ${appHotkey.meta?.name}`
}}
>
Reset
</button>
</td>
</tr>
{/each}
</tbody>
</table>
<p>
Saved: <code>{JSON.stringify(custom.current)}</code>
</p>
<button
type="button"
disabled={recorder.isRecording}
onclick={() => {
custom.resetCustomHotkeys()
message = 'Reset all hotkeys'
}}
>
Reset all
</button>
<p role="status">{message}</p>
</section>
</main>
</div>
{#if import.meta.env.DEV}
<TanStackDevtools plugins={devtoolsPlugins} />
{/if}