Skip to content

Angular Example: InjectHotkeyRecorder

import { Component, signal } from '@angular/core'
import {
  injectFormatForDisplay,
  injectHotkey,
  injectHotkeyRecorder,
  injectHotkeys,
} from '@tanstack/angular-hotkeys'
import type { HotkeyChord } from '@tanstack/angular-hotkeys'

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

  // Shortcut list
  protected readonly listStatus = signal('Not recording')
  protected readonly editing = signal<string | null>(null)
  protected readonly shortcuts = signal<
    Array<{ name: string; hotkey: HotkeyChord | null }>
  >([
    { name: 'Save', hotkey: 'Mod+S' },
    { name: 'Open', hotkey: 'Mod+O' },
    { name: 'Toggle sidebar', hotkey: 'Mod+B' },
  ])

  // One recorder serves every row; `editing` says which row it records for.
  // The callbacks read the signal when they run, so they see the current row.
  // With the default `maxSteps: 1`, the first chord the user presses ends
  // the recording.
  protected readonly listRecorder = injectHotkeyRecorder({
    onRecord: (hotkey) => {
      const editing = this.editing()
      this.shortcuts.update((prev) =>
        prev.map((s) => (s.name === editing ? { ...s, hotkey } : s)),
      )
      this.listStatus.set(`${editing} is now ${hotkey}`)
      this.editing.set(null)
    },
    // Escape, `cancelRecording()`, Tab, or the window losing focus. The old
    // shortcut stays.
    onCancel: () => {
      this.listStatus.set(`${this.editing()} unchanged`)
      this.editing.set(null)
    },
    // Backspace or Delete. The recorder only reports it; this app decides
    // that clearing unbinds the shortcut.
    onClear: () => {
      const editing = this.editing()
      this.shortcuts.update((prev) =>
        prev.map((s) => (s.name === editing ? { ...s, hotkey: null } : s)),
      )
      this.listStatus.set(`${editing} cleared`)
      this.editing.set(null)
    },
  })

  // Validation
  protected readonly validationStatus = signal('Not recording')

  // Return true to accept, or a message to reject. A rejected chord keeps
  // the recorder listening for another one, and `onReject` gets the message.
  protected readonly validationRecorder = injectHotkeyRecorder({
    validate: (_hotkey, { parsedChord }) =>
      parsedChord.modifiers.length > 0 ||
      'Include a modifier, such as Mod or Alt.',
    onReject: ({ reason, message }) =>
      this.validationStatus.set(
        message ? `Rejected: ${message}` : `Rejected (${reason})`,
      ),
    onRecord: (hotkey) => this.validationStatus.set(`Recorded ${hotkey}`),
    onCancel: () => this.validationStatus.set('Cancelled'),
  })

  // Conflicts
  protected readonly conflictsStatus = signal('Not recording')

  // `detectConflicts` rejects a chord that a registered hotkey already uses,
  // including the ones in the shortcut list above. Each conflict carries the
  // registration, so its `meta.name` can name the owner. Without it, the
  // recorder accepts the chord and two hotkeys fire on the same press.
  protected readonly conflictsRecorder = injectHotkeyRecorder({
    detectConflicts: true,
    onReject: ({ reason, hotkey, conflicts }) =>
      this.conflictsStatus.set(
        reason === 'conflict'
          ? `Rejected: ${hotkey} is used by ${conflicts
              ?.map((c) => c.registration.options.meta?.name)
              .join(', ')}`
          : `Rejected (${reason})`,
      ),
    onRecord: (hotkey) => this.conflictsStatus.set(`Recorded ${hotkey}`),
    onCancel: () => this.conflictsStatus.set('Cancelled'),
  })

  // Record by
  protected readonly recordByStatus = signal('Not recording')

  // The default. Writes what the press typed, the way you'd write the hotkey
  // by hand: Shift+/ records `?`, which matches wherever the user's layout
  // types `?`. (`recordBy: 'key'` also writes the typed character, even for
  // macOS Option+S, which types `ß`.)
  protected readonly byTypedKey = injectHotkeyRecorder({
    recordBy: 'auto',
    onRecord: (hotkey) => this.recordByStatus.set(`Recorded ${hotkey}`),
    onCancel: () => this.recordByStatus.set('Cancelled'),
  })

  // Writes the physical key: Shift+/ records `Shift+[Slash]`, which matches
  // that key position on every layout, whatever it types.
  protected readonly byPosition = injectHotkeyRecorder({
    recordBy: 'code',
    onRecord: (hotkey) => this.recordByStatus.set(`Recorded ${hotkey}`),
    onCancel: () => this.recordByStatus.set('Cancelled'),
  })

  // Cancel on blur
  protected readonly blurStatus = signal('Not recording')

  // By default, recording cancels when the window loses focus, as when the
  // user switches apps or tabs. Keys pressed elsewhere never reach the page,
  // so the recorder would otherwise wait for a press that isn't coming.
  protected readonly cancelsOnBlur = injectHotkeyRecorder({
    onRecord: (hotkey) => this.blurStatus.set(`Recorded ${hotkey}`),
    onCancel: () => this.blurStatus.set('Cancelled'),
  })

  // With `cancelOnBlur: false`, recording waits until the user comes back.
  protected readonly keepsRecording = injectHotkeyRecorder({
    cancelOnBlur: false,
    onRecord: (hotkey) => this.blurStatus.set(`Recorded ${hotkey}`),
    onCancel: () => this.blurStatus.set('Cancelled'),
  })

  // Record Tab
  protected readonly tabStatus = signal('Not recording')

  // By default, Tab and Shift+Tab cancel recording and move focus as usual,
  // so a keyboard user can leave the recorder.
  protected readonly tabLeaves = injectHotkeyRecorder({
    onRecord: (hotkey) => this.tabStatus.set(`Recorded ${hotkey}`),
    onCancel: () => this.tabStatus.set('Cancelled'),
  })

  // With `recordTab: true`, Tab and Shift+Tab are recorded like any other
  // chord, and only Escape cancels. Tell users so, as the text below does.
  protected readonly tabRecords = injectHotkeyRecorder({
    recordTab: true,
    onRecord: (hotkey) => this.tabStatus.set(`Recorded ${hotkey}`),
    onCancel: () => this.tabStatus.set('Cancelled'),
  })

  constructor() {
    // The shortcuts are user data held in a signal, so mapping them into one
    // `injectHotkeys` getter is the point here. The hotkeys update when the
    // signal changes, and a null hotkey registers nothing. Mod+S and Mod+O
    // would open the browser's Save and Open dialogs; a matched hotkey calls
    // `preventDefault` by default. While any recorder is recording, these
    // hotkeys pause, so recording Mod+S doesn't also run Save.
    injectHotkeys(() =>
      this.shortcuts().map((s) => ({
        hotkey: s.hotkey,
        callback: () => this.listStatus.set(`Ran ${s.name}`),
        options: { meta: { name: s.name } },
      })),
    )

    injectHotkey(
      'Mod+K',
      () => this.conflictsStatus.set('Ran Command palette'),
      {
        meta: { name: 'Command palette' },
      },
    )
  }

  protected edit(name: string) {
    // Starting while already recording does nothing, so a click on another
    // row moves the recording to that row.
    this.listRecorder.startRecording()
    this.editing.set(name)
    this.listStatus.set(`Recording ${name}`)
  }
}