Skip to content

Angular Example: InjectHotkeys

import { Component, signal } from '@angular/core'
import {
  defineHotkey,
  findHotkeyConflicts,
  injectFormatForDisplay,
  injectHotkeyRegistrations,
  injectHotkeys,
  normalizeHotkey,
  validateHotkey,
} from '@tanstack/angular-hotkeys'
import type { Hotkey, HotkeyIssue } from '@tanstack/angular-hotkeys'

// validateHotkey returns reason codes, so the app writes the messages.
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

@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.component.html',
})
export class AppComponent {
  protected readonly formatForDisplay = injectFormatForDisplay()

  // Register multiple hotkeys
  protected readonly counts = signal({ save: 0, undo: 0, redo: 0 })

  // Check one definition with defineHotkey
  protected readonly pins = signal({ count: 0, modifiers: '' })

  // injectHotkeys gives every array item one type that fits any hotkey, so an
  // item's callback `context` can be a chord or a sequence, and reading
  // `context.parsedChord` needs a `context.kind` check first. defineHotkey
  // types one definition by its hotkey, as injectHotkey types its arguments,
  // and returns it unchanged. Use it for a definition you keep in a variable.
  private readonly pin = defineHotkey({
    hotkey: 'Shift+P',
    // Shift+P is a chord, so `context.parsedChord` needs no kind check.
    callback: (_event, context) =>
      this.pins.update((p) => ({
        count: p.count + 1,
        modifiers: context.parsedChord.modifiers.join('+'),
      })),
    // Chords only: holding Shift+P fires once. Without `requireReset`, key
    // repeat fires it again for as long as the keys are held. `timeout` here
    // would be a type error, because it applies only to sequences.
    options: { requireReset: true, meta: { name: 'Pin' } },
  })

  // Share options
  protected readonly sharedEnabled = signal(true)
  protected readonly sharedCounts = signal({ a: 0, b: 0, c: 0 })

  // Build the list from data
  protected readonly shortcuts = signal<
    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 },
  ])
  protected readonly newHotkey = signal('')
  protected readonly newName = signal('')
  protected readonly message = signal('Add a hotkey to the list.')

  // List the registrations
  // Every registration on the page, chords and sequences. It updates when a
  // hotkey registers, unregisters, changes `enabled`, or fires.
  protected readonly registrations = injectHotkeyRegistrations()

  constructor() {
    // `meta` doesn't change matching. The registrations table below and the
    // devtools read it to name each hotkey.
    injectHotkeys([
      {
        hotkey: 'Shift+S',
        callback: () => this.counts.update((c) => ({ ...c, save: c.save + 1 })),
        options: { meta: { name: 'Save', description: 'Save the document' } },
      },
      {
        hotkey: 'Shift+U',
        callback: () => this.counts.update((c) => ({ ...c, undo: c.undo + 1 })),
        options: {
          meta: { name: 'Undo', description: 'Undo the last action' },
        },
      },
      {
        hotkey: 'Shift+R',
        callback: () => this.counts.update((c) => ({ ...c, redo: c.redo + 1 })),
        options: {
          meta: { name: 'Redo', description: 'Redo the last undone action' },
        },
      },
    ])

    // A defined hotkey and an inline item can share one array.
    injectHotkeys([
      this.pin,
      {
        hotkey: 'Shift+O',
        callback: () => this.pins.set({ count: 0, modifiers: '' }),
        options: { meta: { name: 'Clear pins' } },
      },
    ])

    // The second argument holds options for every item, and an item's own
    // options win. Pass it as a function so it follows the signal: unchecking
    // the box disables Action A and Action B. Action C sets `enabled: true`
    // itself, so it keeps firing.
    // `Alt+[KeyJ]` names the physical J key. On macOS, Option+J types ∆, so a
    // plain `Alt+J` depends on what the layout types there.
    injectHotkeys(
      [
        {
          hotkey: 'Alt+[KeyJ]',
          callback: () =>
            this.sharedCounts.update((c) => ({ ...c, a: c.a + 1 })),
          options: { meta: { name: 'Action A' } },
        },
        {
          hotkey: 'Alt+[KeyK]',
          callback: () =>
            this.sharedCounts.update((c) => ({ ...c, b: c.b + 1 })),
          options: { meta: { name: 'Action B' } },
        },
        {
          hotkey: 'Alt+[KeyL]',
          callback: () =>
            this.sharedCounts.update((c) => ({ ...c, c: c.c + 1 })),
          options: { enabled: true, meta: { name: 'Action C' } },
        },
      ],
      () => ({ enabled: this.sharedEnabled() }),
    )

    // The only place in this example that maps data into the call. The list
    // comes from the user, so its hotkeys aren't known when the code is
    // written. injectHotkey runs once, in the constructor, so it can't follow
    // a list that grows. A getter passed to injectHotkeys can return an array
    // of any length, and the hotkeys update when the signal changes. It
    // matches items by index, so removing one re-registers the items after
    // it, and their counts in the table below start over.
    injectHotkeys(() =>
      this.shortcuts().map((s) => ({
        hotkey: s.hotkey,
        callback: () =>
          this.shortcuts.update((prev) =>
            prev.map((item) =>
              item.id === s.id ? { ...item, count: item.count + 1 } : item,
            ),
          ),
        options: { meta: { name: s.name } },
      })),
    )
  }

  protected addShortcut(event: Event) {
    event.preventDefault()
    const name = this.newName().trim()
    if (!name) {
      this.message.set('Enter a name.')
      return
    }
    // Check the text before registering it. Invalid text doesn't register,
    // and an unknown key, such as a lowercase `escape`, registers but never
    // fires. Both fail silently in production.
    const validation = validateHotkey(this.newHotkey().trim())
    const issues = [...validation.errors, ...validation.warnings]
    if (issues.length > 0) {
      this.message.set(issues.map(issueText).join(' '))
      return
    }
    const hotkey = normalizeHotkey(this.newHotkey().trim())
    // findHotkeyConflicts lists live registrations that the new hotkey would
    // duplicate. Without this check, the duplicate registers anyway, both
    // callbacks run, and the library logs a warning in development.
    const conflicts = findHotkeyConflicts(hotkey)
    if (conflicts.length > 0) {
      this.message.set(
        `Already used by ${conflicts[0].registration.options.meta?.name ?? 'another hotkey'}.`,
      )
      return
    }
    this.shortcuts.update((prev) => [
      ...prev,
      { id: nextId++, hotkey, name, count: 0 },
    ])
    this.message.set(`Added ${name}.`)
    this.newHotkey.set('')
    this.newName.set('')
  }

  protected removeShortcut(id: number) {
    this.shortcuts.update((prev) => prev.filter((item) => item.id !== id))
  }
}