Skip to content

Lit Example: App Hotkeys

import {
  AppHotkeysController,
  FormatForDisplayController,
  HotkeyController,
  HotkeyRecorderController,
  HotkeyRegistrationsController,
  defineAppHotkeys,
  hotkey,
  provideAppHotkeys,
} from '@tanstack/lit-hotkeys'
import { LitElement, css, html, unsafeCSS } from 'lit'
import { customElement, state } from 'lit/decorators.js'
import { createRef, ref } from 'lit/directives/ref.js'
import appStyles from './index.css?raw'
import type { AppHotkeyId } from '@tanstack/lit-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 `AppHotkeysController` and saved custom hotkeys by the ids above, so
// a misspelled id is a type error.
declare module '@tanstack/lit-hotkeys' {
  interface Register {
    appHotkeys: typeof appHotkeys
  }
}

// Lit has no provider component, so publish the app hotkeys before any
// element connects. `customHotkeys` is the user's saved changes, read once
// here. `onCustomHotkeysChange` gets every change, ready to save. Your app
// owns storage, so swap localStorage for a server without other changes.
provideAppHotkeys(appHotkeys, {
  customHotkeys: JSON.parse(
    localStorage.getItem('tanstack-hotkeys-app-hotkeys') ?? '{}',
  ),
  onCustomHotkeysChange: (customHotkeys) =>
    localStorage.setItem(
      'tanstack-hotkeys-app-hotkeys',
      JSON.stringify(customHotkeys),
    ),
})

@customElement('my-app')
export class MyApp extends LitElement {
  static styles = [
    css`
      :host {
        display: block;
        margin: 0;
        font-family: system-ui, -apple-system, sans-serif;
        background: #f5f5f5;
        color: #333;
        box-sizing: border-box;
      }
      :host *,
      :host *::before,
      :host *::after {
        box-sizing: border-box;
      }
    `,
    unsafeCSS(appStyles),
  ]

  @state() private lastAction = ''
  @state() private published = ''
  @state() private result = ''
  @state() private editing: AppHotkeyId | null = null
  @state() private message = 'No changes'

  private note = createRef<HTMLTextAreaElement>()

  private formatForDisplay = new FormatForDisplayController(this)
  // The effective app hotkeys, the app hotkey list, and the user's custom
  // hotkeys. Updates this element when any of them change.
  private app = new AppHotkeysController(this)
  // Mounted registrations, for the toolbar buttons.
  private registrations = new HotkeyRegistrationsController(this)

  // 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.
  private recorder = new HotkeyRecorderController(this, {
    maxSteps: Infinity,
    // Rejecting keeps the recording open with its steps.
    validate: (hotkey, context) => {
      if (!this.editing) return false
      // Pass `context` so a hotkey spelled differently that the same key
      // press fires counts as a conflict.
      const conflicts = this.app.findConflicts(this.editing, hotkey, context)
      return (
        conflicts.length === 0 ||
        `Not changed: used by ${conflicts[0]?.meta?.name}`
      )
    },
    onReject: (rejection) => {
      this.message = rejection.message ?? 'Not changed: try another hotkey'
    },
    onRecord: (hotkey, context) => {
      if (!this.editing) return
      this.app.setCustomHotkey(this.editing, hotkey, context)
      this.message = `Changed ${this.nameOf(this.editing)}`
      this.editing = null
    },
    onClear: () => {
      if (!this.editing) return
      this.app.setCustomHotkey(this.editing, null)
      this.message = `Unassigned ${this.nameOf(this.editing)}`
      this.editing = null
    },
    onCancel: () => {
      this.message = 'Recording cancelled'
      this.editing = null
    },
  })

  constructor() {
    super()
    // 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.
    new HotkeyController(
      this,
      appHotkeys['doc.publish'],
      () => {
        this.published = this.note.value?.value.trim() ?? ''
      },
      {
        // A getter is read on each key press and on `trigger()`. The note is
        // uncontrolled, so a plain boolean would need state that updates
        // this element on every keystroke to stay current.
        enabled: () => !!this.note.value?.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' },
      },
    )
  }

  // Registers a handler by id. The registration follows the user's custom
  // hotkey, because controllers look up the store `provideAppHotkeys`
  // published.
  @hotkey(appHotkeys['doc.save'])
  save() {
    this.lastAction = 'Save'
  }

  @hotkey(appHotkeys['nav.inbox'])
  goToInbox() {
    this.lastAction = 'Go to inbox'
  }

  // Registers nothing while Archive has no hotkey. Once the user assigns one
  // below, this starts firing without any change here.
  @hotkey(appHotkeys['doc.archive'])
  archive() {
    this.lastAction = 'Archive'
  }

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

  render() {
    const formatForDisplay = this.formatForDisplay.format
    // The effective app hotkeys, with the user's changes. The declared
    // `appHotkeys` above only has the defaults, so read labels from here.
    const appHotkeys = this.app.appHotkeys
    const items = this.app.list
    const groups = [...new Set(items.map((item) => item.appHotkey.meta?.group))]
    const customCount = items.filter((item) => item.isCustom).length
    // Mounted registrations of app hotkeys. A registration's meta includes
    // call-site meta, so Publish shows as "Publish note".
    const registrations = this.registrations.hotkeys.filter(
      (reg) => reg.options.appHotkeyId !== undefined,
    )

    return html`
      <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>
          <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>
            <ul>
              <li>
                Save:
                <kbd
                  >${
                    (appHotkeys['doc.save'].hotkey &&
                      formatForDisplay(appHotkeys['doc.save'].hotkey)) ||
                    'Unassigned'
                  }</kbd
                >
              </li>
              <li>
                Go to inbox:
                <kbd
                  >${
                    (appHotkeys['nav.inbox'].hotkey &&
                      formatForDisplay(appHotkeys['nav.inbox'].hotkey)) ||
                    'Unassigned'
                  }</kbd
                >
              </li>
              <li>
                Archive:
                <kbd
                  >${
                    (appHotkeys['doc.archive'].hotkey &&
                      formatForDisplay(appHotkeys['doc.archive'].hotkey)) ||
                    'Unassigned'
                  }</kbd
                >
              </li>
            </ul>
            <p role="status">
              ${this.lastAction ? `Last action: ${this.lastAction}` : 'No action yet'}
            </p>
          </section>

          <section class="demo-section">
            <h2>Enabled getter and call-site meta</h2>
            <p>
              Type a note, then press
              <kbd
                >${
                  (appHotkeys['doc.publish'].hotkey &&
                    formatForDisplay(appHotkeys['doc.publish'].hotkey)) ||
                  'Unassigned'
                }</kbd
              >. Publish does nothing while the note is empty.
            </p>
            <label>
              Note
              <textarea ${ref(this.note)} rows="3"></textarea>
            </label>
            <p role="status">
              ${this.published ? `Published: ${this.published}` : 'Nothing published'}
            </p>
          </section>

          <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">
              ${registrations.map(
                (reg) => html`
                  <button
                    type="button"
                    @click=${() => {
                      const name = reg.options.meta?.name
                      this.result = reg.trigger()
                        ? `Ran: ${name}`
                        : `Not run: ${name}`
                    }}
                  >
                    ${reg.options.meta?.name}
                  </button>
                `,
              )}
            </div>
            <p role="status">${this.result || 'No button clicked'}</p>
          </section>

          <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>
            ${groups.map(
              (group) => html`
                <div>
                  <h3>${group}</h3>
                  <ul>
                    ${items
                      .filter((item) => item.appHotkey.meta?.group === group)
                      .map(
                        ({ appHotkey, isCustom }) => html`
                          <li>
                            ${appHotkey.meta?.name}:
                            <kbd
                              >${
                                (appHotkey.hotkey &&
                                  formatForDisplay(appHotkey.hotkey)) ||
                                'Unassigned'
                              }</kbd
                            >${isCustom ? ' (custom)' : ''}<br /><small
                              >${appHotkey.meta?.description}</small
                            >
                          </li>
                        `,
                      )}
                  </ul>
                </div>
              `,
            )}
            <p role="status">Customized: ${customCount} of ${items.length}</p>
          </section>

          <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>
                ${items.map(
                  ({ appHotkey, isCustom }) => html`
                    <tr>
                      <th scope="row">${appHotkey.meta?.name}</th>
                      <td>
                        <kbd
                          >${
                            this.editing === appHotkey.id
                              ? formatForDisplay(this.recorder.steps) ||
                                'Press keys'
                              : (appHotkey.hotkey &&
                                  formatForDisplay(appHotkey.hotkey)) ||
                                'Unassigned'
                          }</kbd
                        >
                      </td>
                      <td>
                        <button
                          type="button"
                          ?disabled=${this.recorder.isRecording}
                          @click=${() => {
                            this.editing = appHotkey.id
                            this.message = `Recording ${appHotkey.meta?.name}: press keys, then Enter`
                            this.recorder.startRecording()
                          }}
                        >
                          Change
                        </button>
                        <button
                          type="button"
                          ?disabled=${this.recorder.isRecording || !isCustom}
                          @click=${() => {
                            this.app.resetCustomHotkey(appHotkey.id)
                            this.message = `Reset ${appHotkey.meta?.name}`
                          }}
                        >
                          Reset
                        </button>
                      </td>
                    </tr>
                  `,
                )}
              </tbody>
            </table>
            <p>Saved: <code>${JSON.stringify(this.app.customHotkeys)}</code></p>
            <button
              type="button"
              ?disabled=${this.recorder.isRecording}
              @click=${() => {
                this.app.resetCustomHotkeys()
                this.message = 'Reset all hotkeys'
              }}
            >
              Reset all
            </button>
            <p role="status">${this.message}</p>
          </section>
        </main>
      </div>
    `
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'my-app': MyApp
  }
}