import { Component, computed, signal, viewChild } from '@angular/core'
import {
defineAppHotkeys,
injectAppHotkeyList,
injectAppHotkeys,
injectCustomHotkeys,
injectFormatForDisplay,
injectHotkey,
injectHotkeyRecorder,
injectHotkeyRegistrations,
provideHotkeys,
} from '@tanstack/angular-hotkeys'
import type { ElementRef } from '@angular/core'
import type { AppHotkeyId } from '@tanstack/angular-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/angular-hotkeys' {
interface Register {
appHotkeys: typeof appHotkeys
}
}
@Component({
selector: 'app-actions',
standalone: true,
template: `
<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>
@let save = appHotkeys()['doc.save'].hotkey;
@let inbox = appHotkeys()['nav.inbox'].hotkey;
@let archive = appHotkeys()['doc.archive'].hotkey;
<ul>
<li>
Save:
<kbd>{{ (save && formatForDisplay(save)) || 'Unassigned' }}</kbd>
</li>
<li>
Go to inbox:
<kbd>{{ (inbox && formatForDisplay(inbox)) || 'Unassigned' }}</kbd>
</li>
<li>
Archive:
<kbd>{{
(archive && formatForDisplay(archive)) || 'Unassigned'
}}</kbd>
</li>
</ul>
<p role="status">
{{ lastAction() ? 'Last action: ' + lastAction() : 'No action yet' }}
</p>
</section>
`,
})
export class Actions {
readonly appHotkeys = injectAppHotkeys()
readonly formatForDisplay = injectFormatForDisplay()
readonly lastAction = signal('')
constructor() {
injectHotkey(
() => this.appHotkeys()['doc.save'],
() => this.lastAction.set('Save'),
)
injectHotkey(
() => this.appHotkeys()['nav.inbox'],
() => this.lastAction.set('Go to inbox'),
)
injectHotkey(
() => this.appHotkeys()['doc.archive'],
() => this.lastAction.set('Archive'),
)
}
}
@Component({
selector: 'app-publisher',
standalone: true,
template: `
<section class="demo-section">
<h2>Enabled getter and call-site meta</h2>
@let publish = appHotkeys()['doc.publish'].hotkey;
<p>
Type a note, then press
<kbd>{{ (publish && formatForDisplay(publish)) || 'Unassigned' }}</kbd
>. Publish does nothing while the note is empty.
</p>
<label>
Note
<textarea #note rows="3"></textarea>
</label>
<p role="status">
{{ published() ? 'Published: ' + published() : 'Nothing published' }}
</p>
</section>
`,
})
export class Publisher {
readonly appHotkeys = injectAppHotkeys()
readonly formatForDisplay = injectFormatForDisplay()
readonly note = viewChild.required<ElementRef<HTMLTextAreaElement>>('note')
readonly published = signal('')
constructor() {
injectHotkey(
() => this.appHotkeys()['doc.publish'],
() => this.published.set(this.note().nativeElement.value.trim()),
{
enabled: () => !!this.note().nativeElement.value.trim(),
meta: { name: 'Publish note' },
},
)
}
}
@Component({
selector: 'app-toolbar',
standalone: true,
template: `
<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">
@for (reg of registrations(); track reg.id) {
<button
type="button"
(click)="
result.set(
(reg.trigger() ? 'Ran: ' : 'Not run: ') + reg.options.meta?.name
)
"
>
{{ reg.options.meta?.name }}
</button>
}
</div>
<p role="status">{{ result() || 'No button clicked' }}</p>
</section>
`,
})
export class Toolbar {
readonly result = signal('')
readonly allRegistrations = injectHotkeyRegistrations()
readonly registrations = computed(() =>
this.allRegistrations().filter(
(reg) => reg.options.appHotkeyId !== undefined,
),
)
}
@Component({
selector: 'app-cheat-sheet',
standalone: true,
template: `
<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>
@for (group of groups(); track group) {
<div>
<h3>{{ group }}</h3>
<ul>
@for (item of items(); track item.appHotkey.id) {
@if (item.appHotkey.meta?.group === group) {
@let hotkey = item.appHotkey.hotkey;
<li>
{{ item.appHotkey.meta?.name }}:
<kbd>{{
(hotkey && formatForDisplay(hotkey)) || 'Unassigned'
}}</kbd
>{{ item.isCustom ? ' (custom)' : '' }}<br /><small>{{
item.appHotkey.meta?.description
}}</small>
</li>
}
}
</ul>
</div>
}
<p role="status">
Customized: {{ customCount() }} of {{ items().length }}
</p>
</section>
`,
})
export class CheatSheet {
readonly formatForDisplay = injectFormatForDisplay()
readonly items = injectAppHotkeyList()
readonly groups = computed(() => [
...new Set(this.items().map((item) => item.appHotkey.meta?.group)),
])
readonly customCount = computed(
() => this.items().filter((item) => item.isCustom).length,
)
}
@Component({
selector: 'app-settings',
standalone: true,
template: `
<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>
@for (item of items(); track item.appHotkey.id) {
@let hotkey = item.appHotkey.hotkey;
<tr>
<th scope="row">{{ item.appHotkey.meta?.name }}</th>
<td>
<kbd>{{
editing() === item.appHotkey.id
? formatForDisplay(recorder.steps()) || 'Press keys'
: (hotkey && formatForDisplay(hotkey)) || 'Unassigned'
}}</kbd>
</td>
<td>
<button
type="button"
[disabled]="recorder.isRecording()"
(click)="startRecording(item.appHotkey.id)"
>
Change
</button>
<button
type="button"
[disabled]="recorder.isRecording() || !item.isCustom"
(click)="
custom.resetCustomHotkey(item.appHotkey.id);
message.set('Reset ' + item.appHotkey.meta?.name)
"
>
Reset
</button>
</td>
</tr>
}
</tbody>
</table>
<!-- prettier-ignore -->
<p>Saved: <code>{{ saved() }}</code></p>
<button
type="button"
[disabled]="recorder.isRecording()"
(click)="custom.resetCustomHotkeys(); message.set('Reset all hotkeys')"
>
Reset all
</button>
<p role="status">{{ message() }}</p>
</section>
`,
})
export class Settings {
readonly formatForDisplay = injectFormatForDisplay()
readonly items = injectAppHotkeyList()
readonly custom = injectCustomHotkeys()
readonly saved = computed(() => JSON.stringify(this.custom.customHotkeys()))
readonly editing = signal<AppHotkeyId | null>(null)
readonly message = signal('No changes')
readonly recorder = injectHotkeyRecorder({
maxSteps: Infinity,
validate: (hotkey, context) => {
const editing = this.editing()
if (!editing) return false
const conflicts = this.custom.findConflicts(editing, hotkey, context)
return (
conflicts.length === 0 ||
`Not changed: used by ${conflicts[0]?.meta?.name}`
)
},
onReject: (rejection) =>
this.message.set(rejection.message ?? 'Not changed: try another hotkey'),
onRecord: (hotkey, context) => {
const editing = this.editing()
if (!editing) return
this.custom.setCustomHotkey(editing, hotkey, context)
this.message.set(`Changed ${this.nameOf(editing)}`)
this.editing.set(null)
},
onClear: () => {
const editing = this.editing()
if (!editing) return
this.custom.setCustomHotkey(editing, null)
this.message.set(`Unassigned ${this.nameOf(editing)}`)
this.editing.set(null)
},
onCancel: () => {
this.message.set('Recording cancelled')
this.editing.set(null)
},
})
nameOf(id: AppHotkeyId) {
return this.items().find((item) => item.appHotkey.id === id)?.appHotkey.meta
?.name
}
startRecording(id: AppHotkeyId) {
this.editing.set(id)
this.message.set(`Recording ${this.nameOf(id)}: press keys, then Enter`)
this.recorder.startRecording()
}
}
@Component({
selector: 'app-root',
standalone: true,
imports: [Actions, CheatSheet, Publisher, Settings, Toolbar],
providers: [
provideHotkeys({
appHotkeys,
customHotkeys: JSON.parse(
localStorage.getItem('tanstack-hotkeys-app-hotkeys') ?? '{}',
),
onCustomHotkeysChange: (customHotkeys) =>
localStorage.setItem(
'tanstack-hotkeys-app-hotkeys',
JSON.stringify(customHotkeys),
),
}),
],
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>
<app-actions />
<app-publisher />
<app-toolbar />
<app-cheat-sheet />
<app-settings />
</main>
</div>
`,
})
export class AppComponent {}