Skip to content

Angular Example: InjectHotkeyRecorder Sequences

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

// A recorded hotkey as text: `Mod+S` for a chord, `G H` for a sequence. A
// sequence is an array of chords, such as `['G', 'H']`.
function hotkeyText(hotkey: Hotkey) {
  return Array.isArray(hotkey) ? hotkey.join(' ') : hotkey
}

@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: Hotkey | null }>
  >([
    { name: 'Save', hotkey: 'Mod+S' },
    { name: 'Go to inbox', hotkey: ['G', 'I'] },
    { name: 'Go to settings', hotkey: ['G', 'S'] },
  ])

  // With `maxSteps: Infinity`, each chord adds a step and Enter saves. One
  // step saves as a chord string such as 'Mod+S'; two or more save as a
  // sequence such as ['G', 'H']. Backspace removes the last step, and on an
  // empty recording calls `onClear`. Escape cancels. The callbacks read the
  // `editing` signal when they run, so they see the current row.
  protected readonly listRecorder = injectHotkeyRecorder({
    maxSteps: Infinity,
    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 ${hotkeyText(hotkey)}`)
      this.editing.set(null)
    },
    onCancel: () => {
      this.listStatus.set(`${this.editing()} unchanged`)
      this.editing.set(null)
    },
    // The recorder only reports the clear; 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)
    },
  })

  // Max steps
  protected readonly maxStepsStatus = signal('Not recording')

  // Recording saves by itself when it reaches `maxSteps`, here the second
  // chord. Enter still saves a single chord before that.
  protected readonly maxStepsRecorder = injectHotkeyRecorder({
    maxSteps: 2,
    onRecord: (hotkey) =>
      this.maxStepsStatus.set(`Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => this.maxStepsStatus.set('Cancelled'),
  })

  // Commit keys
  protected readonly commitStatus = signal('Not recording')

  // The default, `commitKeys: 'enter'`: plain Enter saves the steps.
  protected readonly enterSaves = injectHotkeyRecorder({
    maxSteps: Infinity,
    commitKeys: 'enter',
    onRecord: (hotkey) =>
      this.commitStatus.set(`Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => this.commitStatus.set('Cancelled'),
  })

  // With `commitKeys: 'none'`, Enter is recorded as a step, so a sequence
  // can end in Enter. Save with `commitRecording()`, `idleTimeoutMs`, or
  // `maxSteps` instead.
  protected readonly enterRecords = injectHotkeyRecorder({
    maxSteps: Infinity,
    commitKeys: 'none',
    onRecord: (hotkey) =>
      this.commitStatus.set(`Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => this.commitStatus.set('Cancelled'),
  })

  // Idle timeout
  protected readonly idleStatus = signal('Not recording')

  // Saves one second after the last chord, so the user doesn't need Enter.
  // Each new chord restarts the wait. Without it, a recording waits for
  // Enter or `maxSteps`.
  protected readonly idleRecorder = injectHotkeyRecorder({
    maxSteps: Infinity,
    idleTimeoutMs: 1000,
    onRecord: (hotkey) => this.idleStatus.set(`Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => this.idleStatus.set('Cancelled'),
  })

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

  // `validate` runs when the recording saves. Check `context.kind` before
  // reading `parsedChord` (one step) or `parsedSequence` (two or more). A
  // rejected recording keeps its steps, so the user can add a chord or press
  // Backspace instead of starting over.
  protected readonly validationRecorder = injectHotkeyRecorder({
    maxSteps: Infinity,
    validate: (_hotkey, context) =>
      context.kind === 'sequence' ||
      context.parsedChord.modifiers.length > 0 ||
      'A single chord needs a modifier.',
    onReject: ({ reason, message }) =>
      this.validationStatus.set(
        message ? `Rejected: ${message}` : `Rejected (${reason})`,
      ),
    onRecord: (hotkey) =>
      this.validationStatus.set(`Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => this.validationStatus.set('Cancelled'),
  })

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

  // `detectConflicts` rejects a recording that a registered hotkey already
  // uses, including prefixes: a chord conflicts with a sequence that starts
  // with it, so `G` conflicts with G I. A sequence conflicts with a chord
  // equal to its first step. G H and G I don't conflict.
  protected readonly conflictsRecorder = injectHotkeyRecorder({
    maxSteps: Infinity,
    detectConflicts: true,
    onReject: ({ reason, hotkey, conflicts }) =>
      this.conflictsStatus.set(
        reason === 'conflict' && hotkey
          ? `Rejected: ${hotkeyText(hotkey)} is used by ${conflicts
              ?.map((c) => c.registration.options.meta?.name)
              .join(', ')}`
          : `Rejected (${reason})`,
      ),
    onRecord: (hotkey) =>
      this.conflictsStatus.set(`Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => this.conflictsStatus.set('Cancelled'),
  })

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

  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}`)
  }
}