Skip to content

Angular Example: InjectHotkey

import { Component, ElementRef, signal, viewChild } from '@angular/core'
import { injectFormatForDisplay, injectHotkey } from '@tanstack/angular-hotkeys'

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

  // Chords as strings and objects
  protected readonly lastBasic = signal('none')

  // Fire once while held
  protected readonly resetCount = signal(0)

  // Fire on key release
  protected readonly previewShown = signal(false)

  // Turn hotkeys on and off
  protected readonly stateEnabled = signal(true)
  protected readonly enabledCounts = signal({ e: 0, g: 0 })
  private readonly getterCheckbox =
    viewChild<ElementRef<HTMLInputElement>>('getterCheckbox')

  // Listen on one element
  protected readonly targetCounts = signal({ panel: 0, drawer: 0 })
  protected readonly drawerOpen = signal(false)
  private readonly panel = viewChild<ElementRef<HTMLDivElement>>('panel')
  // The drawer renders only while it's open. A `viewChild` signal updates
  // when the element appears or goes away, and the hotkey follows it.
  private readonly drawer = viewChild<ElementRef<HTMLDivElement>>('drawer')

  // Typing in text fields
  protected readonly lastInputs = signal('none')

  // The browser's default action
  protected readonly lastPrevent = signal('none')
  private readonly preventInput =
    viewChild<ElementRef<HTMLInputElement>>('preventInput')

  // Stop outer hotkeys
  protected readonly stopPanel = signal(true)
  protected readonly stopCounts = signal({ panel: 0, page: 0 })
  private readonly stopPanelEl =
    viewChild<ElementRef<HTMLDivElement>>('stopPanelEl')

  // Run before a widget's own handler
  protected readonly captureCounts = signal({ bubble: 0, capture: 0 })

  // Keys another listener already handled
  protected readonly handledCounts = signal({ b: 0, i: 0 })

  // Duplicate hotkeys
  protected readonly duplicateCounts = signal({ y: 0, u: 0 })

  constructor() {
    // `hotkey` is the chord as registered, with `Mod` kept. `parsedChord` has
    // `Mod` resolved for this platform: Meta on macOS, Control elsewhere.
    // Mod+S would open the browser's Save dialog. A matched hotkey calls
    // `preventDefault` by default, so the dialog stays closed.
    // `meta` doesn't change matching. The devtools and cheat sheets read it.
    injectHotkey(
      'Mod+S',
      (_event, { hotkey, parsedChord }) =>
        this.lastBasic.set(
          `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
        ),
      { meta: { name: 'Save', description: 'Save the document' } },
    )

    // Function keys, arrow keys, and named keys use their `event.key` names.
    // To match a key by position instead, write its code: 'Mod+[KeyS]'.
    injectHotkey('F2', (_event, { hotkey, parsedChord }) =>
      this.lastBasic.set(
        `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
      ),
    )
    injectHotkey('Alt+ArrowUp', (_event, { hotkey, parsedChord }) =>
      this.lastBasic.set(
        `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
      ),
    )
    injectHotkey('Escape', (_event, { hotkey, parsedChord }) =>
      this.lastBasic.set(
        `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
      ),
    )

    // The same chord as an object, for chords built from data such as
    // modifier checkboxes. `hotkey` reports it as the string 'Mod+Shift+S'.
    injectHotkey(
      { key: 'S', mod: true, shift: true },
      (_event, { hotkey, parsedChord }) =>
        this.lastBasic.set(
          `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
        ),
    )

    // Chords only. Without `requireReset`, holding Mod+K fires again on every
    // key repeat. With it, Mod+K fires once until you release a key.
    injectHotkey('Mod+K', () => this.resetCount.update((count) => count + 1), {
      requireReset: true,
    })

    // Hold Mod+P to show the preview. The keydown hotkey shows it, and the
    // keyup hotkey hides it when you release P or Mod. The two don't conflict
    // because their `eventType` differs. A keyup hotkey still calls
    // `preventDefault` on the keydown, so the print dialog doesn't open.
    injectHotkey('Mod+P', () => this.previewShown.set(true))
    injectHotkey('Mod+P', () => this.previewShown.set(false), {
      eventType: 'keyup',
    })

    // Options passed as a function are reactive: the hotkey updates when a
    // signal read inside it changes. A disabled hotkey stays registered and
    // visible in the devtools. It doesn't call `preventDefault`, so the
    // browser handles Mod+E.
    injectHotkey(
      'Mod+E',
      () =>
        this.enabledCounts.update((counts) => ({ ...counts, e: counts.e + 1 })),
      () => ({ enabled: this.stateEnabled() }),
    )

    // A function passed as `enabled` is read on each key press, for state
    // that no signal tracks. This one reads the checkbox element itself, so
    // toggling it changes no signal. Keep the function cheap: it runs on
    // every key press.
    injectHotkey(
      'Mod+G',
      () =>
        this.enabledCounts.update((counts) => ({ ...counts, g: counts.g + 1 })),
      {
        enabled: () => this.getterCheckbox()?.nativeElement.checked ?? false,
      },
    )

    // An element only gets key events while it or something inside it has
    // focus, so the panel has `tabindex="0"`. Enter does nothing elsewhere.
    injectHotkey(
      'Enter',
      () =>
        this.targetCounts.update((counts) => ({
          ...counts,
          panel: counts.panel + 1,
        })),
      { target: this.panel },
    )

    // While the drawer is closed, its `viewChild` is undefined and nothing is
    // registered. Each target gets its own Enter, so these two don't conflict.
    injectHotkey(
      'Enter',
      () =>
        this.targetCounts.update((counts) => ({
          ...counts,
          drawer: counts.drawer + 1,
        })),
      { target: this.drawer },
    )

    // The default `ignoreInputs: 'auto'` decides from the hotkey. A key that
    // types or edits text, such as N, Shift+N, Alt+N, or an arrow key, is
    // skipped while a text field has focus, so N types into the field.
    injectHotkey('N', (_event, { hotkey }) => this.lastInputs.set(hotkey))

    // With 'auto', Control and Meta chords, Escape, and function keys fire in
    // text fields too, because they type nothing.
    injectHotkey('Mod+Enter', (_event, { hotkey }) =>
      this.lastInputs.set(hotkey),
    )

    // `true` skips text fields for every hotkey. Mod+A then selects the field's
    // text, and selects nothing on the rest of the page.
    injectHotkey('Mod+A', (_event, { hotkey }) => this.lastInputs.set(hotkey), {
      ignoreInputs: true,
    })

    // `false` fires in text fields too. 'auto' would skip Shift+Enter there.
    injectHotkey(
      'Shift+Enter',
      (_event, { hotkey }) => this.lastInputs.set(hotkey),
      { ignoreInputs: false },
    )

    // These hotkeys listen on the text field. A hotkey targeted at a field
    // always gets its keys, whatever `ignoreInputs` says. By default a matched
    // hotkey calls `preventDefault`, so 1 doesn't type.
    injectHotkey('1', (_event, { hotkey }) => this.lastPrevent.set(hotkey), {
      target: this.preventInput,
    })

    // `false` lets the browser act too, so 2 fires the hotkey and types.
    injectHotkey('2', (_event, { hotkey }) => this.lastPrevent.set(hotkey), {
      target: this.preventInput,
      preventDefault: false,
    })

    // A disabled hotkey normally leaves the key to the browser. `'always'`
    // keeps calling `preventDefault` while the hotkey is disabled, so 3 doesn't
    // type and the callback doesn't run.
    injectHotkey('3', (_event, { hotkey }) => this.lastPrevent.set(hotkey), {
      target: this.preventInput,
      enabled: false,
      preventDefault: 'always',
    })

    // With focus inside the panel, its hotkey runs before the page's hotkey
    // for the same key. `stopPropagation: true`, the default, stops the event
    // there, so the page's Mod+D doesn't fire. With `false`, both fire.
    injectHotkey(
      'Mod+D',
      () =>
        this.stopCounts.update((counts) => ({
          ...counts,
          panel: counts.panel + 1,
        })),
      () => ({ target: this.stopPanelEl, stopPropagation: this.stopPanel() }),
    )
    injectHotkey('Mod+D', () =>
      this.stopCounts.update((counts) => ({
        ...counts,
        page: counts.page + 1,
      })),
    )

    // Hotkeys listen in the bubble phase, after the focused element's own
    // handlers. The widget below calls `stopPropagation` on every key, so
    // Mod+ArrowUp never reaches the page while the widget has focus.
    injectHotkey('Mod+ArrowUp', () =>
      this.captureCounts.update((counts) => ({
        ...counts,
        bubble: counts.bubble + 1,
      })),
    )

    // `capture: true` runs the hotkey on the way down, before the widget's
    // handler. With the default `stopPropagation: true`, the widget then
    // doesn't see Mod+ArrowDown at all.
    injectHotkey(
      'Mod+ArrowDown',
      () =>
        this.captureCounts.update((counts) => ({
          ...counts,
          capture: counts.capture + 1,
        })),
      { capture: true },
    )

    // The editor below calls `preventDefault` on its Control and Meta chords,
    // as rich text editors do for Mod+B. With `ignoreDefaultPrevented: true`,
    // the hotkey skips a key press that another listener already prevented.
    injectHotkey(
      'Mod+B',
      () =>
        this.handledCounts.update((counts) => ({ ...counts, b: counts.b + 1 })),
      { ignoreDefaultPrevented: true },
    )

    // By default a hotkey fires even when the key was already prevented.
    injectHotkey('Mod+I', () =>
      this.handledCounts.update((counts) => ({ ...counts, i: counts.i + 1 })),
    )

    // Two registrations of the same hotkey on the same target both run.
    // `conflictBehavior` is checked when the second one registers, so set it
    // on each registration that may register second. 'allow' registers both
    // silently.
    injectHotkey(
      'Mod+Y',
      () =>
        this.duplicateCounts.update((counts) => ({
          ...counts,
          y: counts.y + 1,
        })),
      { conflictBehavior: 'allow' },
    )
    injectHotkey(
      'Mod+Y',
      () =>
        this.duplicateCounts.update((counts) => ({
          ...counts,
          y: counts.y + 1,
        })),
      { conflictBehavior: 'allow' },
    )

    // The default, 'warn', also registers both, and logs
    // "[hotkeys] 'Mod+U' is already registered" in development. This example
    // triggers that warning on purpose. 'error' throws when the second one
    // registers instead.
    injectHotkey('Mod+U', () =>
      this.duplicateCounts.update((counts) => ({ ...counts, u: counts.u + 1 })),
    )
    injectHotkey('Mod+U', () =>
      this.duplicateCounts.update((counts) => ({ ...counts, u: counts.u + 1 })),
    )
  }

  // Stands in for a rich text editor that handles its own chords.
  protected preventModChords(event: KeyboardEvent) {
    if (event.ctrlKey || event.metaKey) event.preventDefault()
  }
}