Skip to content

Angular Example: InjectHeldKeys

import { Component, computed, effect, signal } from '@angular/core'
import {
  injectFormatForDisplay,
  injectHeldKeyCodes,
  injectHeldKeys,
  injectHotkey,
  injectHotkeyHint,
} from '@tanstack/angular-hotkeys'

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <div class="app">
      <header>
        <h1>injectHeldKeys</h1>
        <p>
          Track which keys the user is holding, and show a hotkey's label only
          while its modifiers are held.
        </p>
      </header>

      <main>
        <section class="demo-section">
          <h2>Held keys</h2>
          <p>
            Hold <kbd>Shift</kbd> + <kbd>Control</kbd> + <kbd>A</kbd>, or press
            several letters at once, then release them one by one.
          </p>
          <div class="key-display" aria-hidden="true">
            @for (key of heldKeys(); track $index) {
              <!-- { key } formats a raw event.key value, such as 'Control' as
                   ⌃ on macOS. -->
              <kbd class="large">{{ formatForDisplay({ key: key }) }}</kbd>
            }
          </div>
          <p role="status">
            {{
              heldKeys().length > 0
                ? 'Held: ' + heldKeys().join(' + ')
                : 'No keys held'
            }}
          </p>
        </section>

        <section class="demo-section">
          <h2>Held key codes</h2>
          <p>
            The physical key behind each held key. Left and right
            <kbd>Shift</kbd> both hold <code>Shift</code>, with different codes.
          </p>
          <p role="status">
            {{ heldKeys().length > 0 ? heldCodesText() : 'No keys held' }}
          </p>
        </section>

        <section class="demo-section">
          <h2>Hotkey hints</h2>
          <p>
            Hold <kbd>{{ formatForDisplay('Mod') }}</kbd
            >, <kbd>Shift</kbd>, or both to see which shortcuts they lead to.
          </p>
          <div class="toolbar">
            <button (click)="lastAction.set('Save')">
              Save
              @if (showSaveHint()) {
                <kbd>{{ formatForDisplay('Mod+S') }}</kbd>
              }
            </button>
            <button (click)="lastAction.set('Bold')">
              Bold
              @if (showBoldHint()) {
                <kbd>{{ formatForDisplay('Mod+B') }}</kbd>
              }
            </button>
            <button (click)="lastAction.set('Export')">
              Export
              @if (showExportHint()) {
                <kbd>{{ formatForDisplay('Mod+Shift+E') }}</kbd>
              }
            </button>
            <button (click)="lastAction.set('Archive')">
              Archive
              @if (showArchiveHint()) {
                <kbd>{{ formatForDisplay('Mod+Shift+A') }}</kbd>
              }
            </button>
          </div>
          <label>
            <input
              #checkbox
              type="checkbox"
              [checked]="boldEnabled()"
              (change)="boldEnabled.set(checkbox.checked)"
            />
            Enable Bold
          </label>
          <p>Last action: {{ lastAction() }}</p>
          <p role="status">
            {{
              shownHints().length > 0
                ? 'Hints shown: ' + shownHints().join(', ')
                : 'Hints shown: none'
            }}
          </p>
        </section>

        <section class="demo-section">
          <h2>Recent combinations</h2>
          <p>
            Each entry is the most keys you held at once, added when you release
            them all.
          </p>
          <p role="status">
            Recorded {{ history().length }}
            {{ history().length === 1 ? 'combination' : 'combinations' }}
          </p>
          <ol class="history-list">
            @for (combination of history(); track $index) {
              <li>{{ combination }}</li>
            }
          </ol>
          <button (click)="history.set([])">Clear history</button>
        </section>
      </main>
    </div>
  `,
})
export class AppComponent {
  readonly formatForDisplay = injectFormatForDisplay()
  // Held keys in press order, such as ['Shift', 'A']. Updates on every
  // keydown and keyup, and empties when the window loses focus.
  readonly heldKeys = injectHeldKeys()
  // Each held key's physical `event.code`, such as { Shift: 'ShiftLeft' }.
  readonly heldCodes = injectHeldKeyCodes()
  readonly heldCodesText = computed(() =>
    this.heldKeys()
      .map((key) => `${key}: ${this.heldCodes()[key]}`)
      .join(', '),
  )

  readonly history = signal<Array<string>>([])
  readonly lastAction = signal('none')
  readonly boldEnabled = signal(true)

  // True while the user holds Mod, and the Mod+S below can fire. The hint
  // registers nothing: it reads the held keys and the registrations.
  readonly showSaveHint = injectHotkeyHint('Mod+S')
  // False while Bold is disabled, even with Mod held, because no enabled
  // registration of Mod+B can fire.
  readonly showBoldHint = injectHotkeyHint('Mod+B')
  // True while the user holds Mod, Shift, or both. Holding a modifier the
  // hotkey doesn't use, such as Alt, hides it.
  readonly showExportHint = injectHotkeyHint('Mod+Shift+E')
  // With `exact: true`, only Mod and Shift held together show the hint.
  // Without it, Mod or Shift alone would show it, as for Export.
  readonly showArchiveHint = injectHotkeyHint('Mod+Shift+A', { exact: true })

  readonly shownHints = computed(() =>
    [
      this.showSaveHint() && 'Save',
      this.showBoldHint() && 'Bold',
      this.showExportHint() && 'Export',
      this.showArchiveHint() && 'Archive',
    ].filter(Boolean),
  )

  // The most keys held at once since nothing was held.
  #mostHeld: Array<string> = []

  constructor() {
    // Once every key is released, records the most keys held at once, such
    // as 'Shift + Control + A', and keeps the last 10.
    effect(() => {
      const heldKeys = this.heldKeys()
      if (heldKeys.length > this.#mostHeld.length) this.#mostHeld = heldKeys
      if (heldKeys.length > 0 || this.#mostHeld.length === 0) return
      const combination = this.#mostHeld.join(' + ')
      this.#mostHeld = []
      this.history.update((h) => [...h.slice(-9), combination])
    })

    // Mod+S would open the browser's Save dialog. A matched hotkey calls
    // `preventDefault` by default, so the page handles it instead.
    injectHotkey('Mod+S', () => this.lastAction.set('Save'))
    // While `enabled` is false, Mod+B doesn't fire, and its hint stays
    // hidden. The options getter re-runs when `boldEnabled` changes.
    injectHotkey(
      'Mod+B',
      () => this.lastAction.set('Bold'),
      () => ({ enabled: this.boldEnabled() }),
    )
    injectHotkey('Mod+Shift+E', () => this.lastAction.set('Export'))
    injectHotkey('Mod+Shift+A', () => this.lastAction.set('Archive'))
  }
}