Skip to content

Angular Example: App Hotkeys

import { Component, computed, signal, viewChild } from '@angular/core'
import {
  defineAppHotkeys,
  injectAppHotkeyList,
  injectAppHotkeys,
  injectCustomHotkeys,
  injectFormatForDisplay,
  injectHotkey,
  injectHotkeyRecorder,
  injectHotkeyRegistrations,
  provideHotkeys,
} from '@tanstack/angular-hotkeys'
import type { ElementRef } from '@angular/core'
import type { AppHotkeyId } from '@tanstack/angular-hotkeys'

// A large app can declare hotkeys next to the feature that owns them, then
// spread them into the one object it provides. Each entry keeps its id and
// the kind of its default, so `timeout` stays a sequence option here.
const navigationHotkeys = defineAppHotkeys({
  'nav.inbox': {
    hotkey: ['G', 'I'],
    meta: {
      name: 'Go to inbox',
      description: 'Press G, then I',
      group: 'Navigation',
    },
    // Sequences only. Without it, each key must follow within 1000 ms.
    options: { timeout: 1500 },
  },
})

// Every hotkey in the app, declared once. The keys ('doc.save') are ids:
// saved custom hotkeys refer to them, so keep them stable. The guide puts
// this in its own module that loads with the app shell; it lives here so the
// whole example is in one file.
const appHotkeys = defineAppHotkeys({
  'doc.save': {
    hotkey: 'Mod+S',
    meta: { name: 'Save', description: 'Saves the note', group: 'Document' },
    // Chords only. Without it, holding Mod+S saves again on every key repeat.
    // Mod+S would open the browser's Save dialog; a matched hotkey calls
    // `preventDefault` by default.
    options: { requireReset: true },
  },
  'doc.publish': {
    hotkey: 'Mod+Enter',
    meta: {
      name: 'Publish',
      description: 'Works only while the note has text',
      group: 'Document',
    },
  },
  // `null` declares an action with no default hotkey. It registers nothing
  // until the user assigns one.
  'doc.archive': {
    hotkey: null,
    meta: {
      name: 'Archive',
      description: 'No default hotkey',
      group: 'Document',
    },
  },
  ...navigationHotkeys,
})

// Types `injectAppHotkeys()`, `injectCustomHotkeys()`, and saved custom
// hotkeys by the ids above, so a misspelled id is a type error.
declare module '@tanstack/angular-hotkeys' {
  interface Register {
    appHotkeys: typeof appHotkeys
  }
}

/** Registers handlers by id. The provider supplies each id's current hotkey. */
@Component({
  selector: 'app-actions',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Register app hotkeys</h2>
      <p>
        Components register a handler for an app hotkey by its id. The labels
        follow the hotkeys you change below.
      </p>
      @let save = appHotkeys()['doc.save'].hotkey;
      @let inbox = appHotkeys()['nav.inbox'].hotkey;
      @let archive = appHotkeys()['doc.archive'].hotkey;
      <ul>
        <li>
          Save:
          <kbd>{{ (save && formatForDisplay(save)) || 'Unassigned' }}</kbd>
        </li>
        <li>
          Go to inbox:
          <kbd>{{ (inbox && formatForDisplay(inbox)) || 'Unassigned' }}</kbd>
        </li>
        <li>
          Archive:
          <kbd>{{
            (archive && formatForDisplay(archive)) || 'Unassigned'
          }}</kbd>
        </li>
      </ul>
      <p role="status">
        {{ lastAction() ? 'Last action: ' + lastAction() : 'No action yet' }}
      </p>
    </section>
  `,
})
export class Actions {
  // A signal of the effective app hotkeys: the declarations with the user's
  // custom hotkeys applied.
  readonly appHotkeys = injectAppHotkeys()
  readonly formatForDisplay = injectFormatForDisplay()
  readonly lastAction = signal('')

  constructor() {
    injectHotkey(
      () => this.appHotkeys()['doc.save'],
      () => this.lastAction.set('Save'),
    )
    injectHotkey(
      () => this.appHotkeys()['nav.inbox'],
      () => this.lastAction.set('Go to inbox'),
    )
    // Registers nothing while Archive has no hotkey. Once the user assigns
    // one below, this starts firing without any change here.
    injectHotkey(
      () => this.appHotkeys()['doc.archive'],
      () => this.lastAction.set('Archive'),
    )
  }
}

/** An `enabled` getter, and `meta` added for this registration only. */
@Component({
  selector: 'app-publisher',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Enabled getter and call-site meta</h2>
      @let publish = appHotkeys()['doc.publish'].hotkey;
      <p>
        Type a note, then press
        <kbd>{{ (publish && formatForDisplay(publish)) || 'Unassigned' }}</kbd
        >. Publish does nothing while the note is empty.
      </p>
      <label>
        Note
        <textarea #note rows="3"></textarea>
      </label>
      <p role="status">
        {{ published() ? 'Published: ' + published() : 'Nothing published' }}
      </p>
    </section>
  `,
})
export class Publisher {
  readonly appHotkeys = injectAppHotkeys()
  readonly formatForDisplay = injectFormatForDisplay()
  readonly note = viewChild.required<ElementRef<HTMLTextAreaElement>>('note')
  readonly published = signal('')

  constructor() {
    // The default `ignoreInputs: 'auto'` lets Mod shortcuts fire in text
    // fields, so Mod+Enter works while typing in the note. The hotkey calls
    // `preventDefault`, so the textarea gets no new line.
    injectHotkey(
      () => this.appHotkeys()['doc.publish'],
      () => this.published.set(this.note().nativeElement.value.trim()),
      {
        // A getter is read on each key press and on `trigger()`. The note is
        // uncontrolled, so a plain boolean would need a signal that updates
        // on every keystroke to stay current.
        enabled: () => !!this.note().nativeElement.value.trim(),
        // Merged over the declared meta for this registration only.
        // Registration lists, such as the buttons below, show "Publish note";
        // the cheat sheet keeps the declared "Publish".
        meta: { name: 'Publish note' },
      },
    )
  }
}

/** Runs registered app hotkeys from buttons, without a key press. */
@Component({
  selector: 'app-toolbar',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Run actions without a key press</h2>
      <p>
        Each button calls the registration's <code>trigger()</code>, which runs
        its handler and returns whether it ran. It checks only
        <code>enabled</code>.
      </p>
      <div class="toolbar">
        @for (reg of registrations(); track reg.id) {
          <button
            type="button"
            (click)="
              result.set(
                (reg.trigger() ? 'Ran: ' : 'Not run: ') + reg.options.meta?.name
              )
            "
          >
            {{ reg.options.meta?.name }}
          </button>
        }
      </div>
      <p role="status">{{ result() || 'No button clicked' }}</p>
    </section>
  `,
})
export class Toolbar {
  readonly result = signal('')
  // Mounted registrations of app hotkeys. A registration's meta includes
  // call-site meta, so Publish shows as "Publish note".
  readonly allRegistrations = injectHotkeyRegistrations()
  readonly registrations = computed(() =>
    this.allRegistrations().filter(
      (reg) => reg.options.appHotkeyId !== undefined,
    ),
  )
}

/** Lists every app hotkey, mounted or not, grouped by `meta.group`. */
@Component({
  selector: 'app-cheat-sheet',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Cheat sheet</h2>
      <p>
        Lists every app hotkey, including ones no mounted component registers,
        such as Archive before it has a hotkey.
      </p>
      @for (group of groups(); track group) {
        <div>
          <h3>{{ group }}</h3>
          <ul>
            @for (item of items(); track item.appHotkey.id) {
              @if (item.appHotkey.meta?.group === group) {
                @let hotkey = item.appHotkey.hotkey;
                <li>
                  {{ item.appHotkey.meta?.name }}:
                  <kbd>{{
                    (hotkey && formatForDisplay(hotkey)) || 'Unassigned'
                  }}</kbd
                  >{{ item.isCustom ? ' (custom)' : '' }}<br /><small>{{
                    item.appHotkey.meta?.description
                  }}</small>
                </li>
              }
            }
          </ul>
        </div>
      }
      <p role="status">
        Customized: {{ customCount() }} of {{ items().length }}
      </p>
    </section>
  `,
})
export class CheatSheet {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly items = injectAppHotkeyList()
  readonly groups = computed(() => [
    ...new Set(this.items().map((item) => item.appHotkey.meta?.group)),
  ])
  readonly customCount = computed(
    () => this.items().filter((item) => item.isCustom).length,
  )
}

/** Rebinds app hotkeys. The provider saves each change. */
@Component({
  selector: 'app-settings',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Change hotkeys</h2>
      <p>
        Changes are saved to <code>localStorage</code> and survive a reload.
        Only differences from the declared defaults are saved, so users who
        never changed a hotkey get your new defaults.
      </p>
      <table>
        <tbody>
          @for (item of items(); track item.appHotkey.id) {
            @let hotkey = item.appHotkey.hotkey;
            <tr>
              <th scope="row">{{ item.appHotkey.meta?.name }}</th>
              <td>
                <kbd>{{
                  editing() === item.appHotkey.id
                    ? formatForDisplay(recorder.steps()) || 'Press keys'
                    : (hotkey && formatForDisplay(hotkey)) || 'Unassigned'
                }}</kbd>
              </td>
              <td>
                <button
                  type="button"
                  [disabled]="recorder.isRecording()"
                  (click)="startRecording(item.appHotkey.id)"
                >
                  Change
                </button>
                <button
                  type="button"
                  [disabled]="recorder.isRecording() || !item.isCustom"
                  (click)="
                    custom.resetCustomHotkey(item.appHotkey.id);
                    message.set('Reset ' + item.appHotkey.meta?.name)
                  "
                >
                  Reset
                </button>
              </td>
            </tr>
          }
        </tbody>
      </table>
      <!-- prettier-ignore -->
      <p>Saved: <code>{{ saved() }}</code></p>
      <button
        type="button"
        [disabled]="recorder.isRecording()"
        (click)="custom.resetCustomHotkeys(); message.set('Reset all hotkeys')"
      >
        Reset all
      </button>
      <p role="status">{{ message() }}</p>
    </section>
  `,
})
export class Settings {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly items = injectAppHotkeyList()
  // `customHotkeys` is a signal; the rest are actions.
  readonly custom = injectCustomHotkeys()
  readonly saved = computed(() => JSON.stringify(this.custom.customHotkeys()))
  readonly editing = signal<AppHotkeyId | null>(null)
  readonly message = signal('No changes')

  // One recorder for every row. `maxSteps: Infinity` records a chord or a
  // sequence: press each chord, then Enter. Escape cancels. Backspace with
  // nothing recorded clears the hotkey. App hotkeys don't fire while it
  // records. The callbacks read `editing` when they run, so they act on the
  // row that started recording.
  readonly recorder = injectHotkeyRecorder({
    maxSteps: Infinity,
    // Rejecting keeps the recording open with its steps.
    validate: (hotkey, context) => {
      const editing = this.editing()
      if (!editing) return false
      // Pass `context` so a hotkey spelled differently that the same key
      // press fires counts as a conflict.
      const conflicts = this.custom.findConflicts(editing, hotkey, context)
      return (
        conflicts.length === 0 ||
        `Not changed: used by ${conflicts[0]?.meta?.name}`
      )
    },
    onReject: (rejection) =>
      this.message.set(rejection.message ?? 'Not changed: try another hotkey'),
    onRecord: (hotkey, context) => {
      const editing = this.editing()
      if (!editing) return
      this.custom.setCustomHotkey(editing, hotkey, context)
      this.message.set(`Changed ${this.nameOf(editing)}`)
      this.editing.set(null)
    },
    onClear: () => {
      const editing = this.editing()
      if (!editing) return
      this.custom.setCustomHotkey(editing, null)
      this.message.set(`Unassigned ${this.nameOf(editing)}`)
      this.editing.set(null)
    },
    onCancel: () => {
      this.message.set('Recording cancelled')
      this.editing.set(null)
    },
  })

  nameOf(id: AppHotkeyId) {
    return this.items().find((item) => item.appHotkey.id === id)?.appHotkey.meta
      ?.name
  }

  startRecording(id: AppHotkeyId) {
    this.editing.set(id)
    this.message.set(`Recording ${this.nameOf(id)}: press keys, then Enter`)
    this.recorder.startRecording()
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [Actions, CheatSheet, Publisher, Settings, Toolbar],
  // An app usually provides this in its application config. It's here so the
  // whole example is in one file; every component below can inject it.
  // `customHotkeys` is the user's saved changes, read once at startup.
  // `onCustomHotkeysChange` gets every change, ready to save. Your app owns
  // storage, so swap localStorage for a server without other changes.
  providers: [
    provideHotkeys({
      appHotkeys,
      customHotkeys: JSON.parse(
        localStorage.getItem('tanstack-hotkeys-app-hotkeys') ?? '{}',
      ),
      onCustomHotkeysChange: (customHotkeys) =>
        localStorage.setItem(
          'tanstack-hotkeys-app-hotkeys',
          JSON.stringify(customHotkeys),
        ),
    }),
  ],
  template: `
    <div class="app">
      <header>
        <h1>App Hotkeys</h1>
        <p>
          Declare every hotkey once with <code>defineAppHotkeys</code>, register
          handlers by id, list them in a cheat sheet, and let users change them.
        </p>
      </header>

      <main>
        <app-actions />
        <app-publisher />
        <app-toolbar />
        <app-cheat-sheet />
        <app-settings />
      </main>
    </div>
  `,
})
export class AppComponent {}