Skip to content

Lit Example: Hotkey Recorder

import {
  FormatForDisplayController,
  HotkeyController,
  HotkeyRecorderController,
  hotkey,
} from '@tanstack/lit-hotkeys'
import { LitElement, css, html, unsafeCSS } from 'lit'
import { customElement, state } from 'lit/decorators.js'
import appStyles from './index.css?raw'
import type { HotkeyChord } from '@tanstack/lit-hotkeys'

@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),
  ]

  private formatForDisplay = new FormatForDisplayController(this)

  // Shortcut list
  @state() private listStatus = 'Not recording'
  @state() private editing: string | null = null
  @state() private shortcuts: Array<{
    name: string
    hotkey: HotkeyChord | null
  }> = [
    { name: 'Save', hotkey: 'Mod+S' },
    { name: 'Open', hotkey: 'Mod+O' },
    { name: 'Toggle sidebar', hotkey: 'Mod+B' },
  ]

  // One recorder serves every row; `editing` says which row it records for.
  // With the default `maxSteps: 1`, the first chord the user presses ends
  // the recording. The callbacks read `this.editing` when they run.
  private listRecorder = new HotkeyRecorderController(this, {
    onRecord: (hotkey) => {
      this.shortcuts = this.shortcuts.map((s) =>
        s.name === this.editing ? { ...s, hotkey } : s,
      )
      this.listStatus = `${this.editing} is now ${hotkey}`
      this.editing = null
    },
    // Escape, `cancelRecording()`, Tab, or the window losing focus. The old
    // shortcut stays.
    onCancel: () => {
      this.listStatus = `${this.editing} unchanged`
      this.editing = null
    },
    // Backspace or Delete. The recorder only reports it; this app decides
    // that clearing unbinds the shortcut.
    onClear: () => {
      this.shortcuts = this.shortcuts.map((s) =>
        s.name === this.editing ? { ...s, hotkey: null } : s,
      )
      this.listStatus = `${this.editing} cleared`
      this.editing = null
    },
  })

  constructor() {
    super()
    // Lit has no API that registers a list of hotkeys, so each row gets its
    // own `HotkeyController`. The hotkey function reads the row's current
    // hotkey after each update, so a recorded shortcut replaces the old one.
    // A null hotkey registers nothing. Mod+S and Mod+O would open the
    // browser's Save and Open dialogs; a matched hotkey calls
    // `preventDefault` by default. While any recorder is recording, these
    // hotkeys pause, so recording Mod+S doesn't also run Save.
    for (const { name } of this.shortcuts) {
      new HotkeyController(
        this,
        () => this.shortcuts.find((s) => s.name === name)?.hotkey,
        () => (this.listStatus = `Ran ${name}`),
        { meta: { name } },
      )
    }
  }

  // Validation
  @state() private validationStatus = 'Not recording'

  // Return true to accept, or a message to reject. A rejected chord keeps
  // the recorder listening for another one, and `onReject` gets the message.
  private validationRecorder = new HotkeyRecorderController(this, {
    validate: (_hotkey, { parsedChord }) =>
      parsedChord.modifiers.length > 0 ||
      'Include a modifier, such as Mod or Alt.',
    onReject: ({ reason, message }) =>
      (this.validationStatus = message
        ? `Rejected: ${message}`
        : `Rejected (${reason})`),
    onRecord: (hotkey) => (this.validationStatus = `Recorded ${hotkey}`),
    onCancel: () => (this.validationStatus = 'Cancelled'),
  })

  // Conflicts
  @state() private conflictsStatus = 'Not recording'

  @hotkey('Mod+K', { meta: { name: 'Command palette' } })
  openCommandPalette() {
    this.conflictsStatus = 'Ran Command palette'
  }

  // `detectConflicts` rejects a chord that a registered hotkey already uses,
  // including the ones in the shortcut list above. Each conflict carries the
  // registration, so its `meta.name` can name the owner. Without it, the
  // recorder accepts the chord and two hotkeys fire on the same press.
  private conflictsRecorder = new HotkeyRecorderController(this, {
    detectConflicts: true,
    onReject: ({ reason, hotkey, conflicts }) =>
      (this.conflictsStatus =
        reason === 'conflict'
          ? `Rejected: ${hotkey} is used by ${conflicts
              ?.map((c) => c.registration.options.meta?.name)
              .join(', ')}`
          : `Rejected (${reason})`),
    onRecord: (hotkey) => (this.conflictsStatus = `Recorded ${hotkey}`),
    onCancel: () => (this.conflictsStatus = 'Cancelled'),
  })

  // Record by
  @state() private recordByStatus = 'Not recording'

  // The default. Writes what the press typed, the way you'd write the hotkey
  // by hand: Shift+/ records `?`, which matches wherever the user's layout
  // types `?`. (`recordBy: 'key'` also writes the typed character, even for
  // macOS Option+S, which types `ß`.)
  private byTypedKey = new HotkeyRecorderController(this, {
    recordBy: 'auto',
    onRecord: (hotkey) => (this.recordByStatus = `Recorded ${hotkey}`),
    onCancel: () => (this.recordByStatus = 'Cancelled'),
  })

  // Writes the physical key: Shift+/ records `Shift+[Slash]`, which matches
  // that key position on every layout, whatever it types.
  private byPosition = new HotkeyRecorderController(this, {
    recordBy: 'code',
    onRecord: (hotkey) => (this.recordByStatus = `Recorded ${hotkey}`),
    onCancel: () => (this.recordByStatus = 'Cancelled'),
  })

  // Cancel on blur
  @state() private blurStatus = 'Not recording'

  // By default, recording cancels when the window loses focus, as when the
  // user switches apps or tabs. Keys pressed elsewhere never reach the page,
  // so the recorder would otherwise wait for a press that isn't coming.
  private cancelsOnBlur = new HotkeyRecorderController(this, {
    onRecord: (hotkey) => (this.blurStatus = `Recorded ${hotkey}`),
    onCancel: () => (this.blurStatus = 'Cancelled'),
  })

  // With `cancelOnBlur: false`, recording waits until the user comes back.
  private keepsRecording = new HotkeyRecorderController(this, {
    cancelOnBlur: false,
    onRecord: (hotkey) => (this.blurStatus = `Recorded ${hotkey}`),
    onCancel: () => (this.blurStatus = 'Cancelled'),
  })

  // Record Tab
  @state() private tabStatus = 'Not recording'

  // By default, Tab and Shift+Tab cancel recording and move focus as usual,
  // so a keyboard user can leave the recorder.
  private tabLeaves = new HotkeyRecorderController(this, {
    onRecord: (hotkey) => (this.tabStatus = `Recorded ${hotkey}`),
    onCancel: () => (this.tabStatus = 'Cancelled'),
  })

  // With `recordTab: true`, Tab and Shift+Tab are recorded like any other
  // chord, and only Escape cancels. Tell users so, as the text below does.
  private tabRecords = new HotkeyRecorderController(this, {
    recordTab: true,
    onRecord: (hotkey) => (this.tabStatus = `Recorded ${hotkey}`),
    onCancel: () => (this.tabStatus = 'Cancelled'),
  })

  render() {
    const formatForDisplay = this.formatForDisplay.format

    return html`
      <div class="app">
        <header>
          <h1>Hotkey Recorder</h1>
          <p>
            <code>HotkeyRecorderController</code> records the next key
            combination the user presses. Each section shows one recorder
            option.
          </p>
        </header>

        <main>
          <section class="demo-section">
            <h2>Shortcut list</h2>
            <p>
              Click Edit, then press a key combination. Escape cancels and keeps
              the old shortcut. Backspace or Delete clears it.
            </p>
            <ul class="shortcut-list">
              ${this.shortcuts.map((s) => {
                const recording =
                  this.editing === s.name && this.listRecorder.isRecording
                return html`
                  <li>
                    <span>${s.name}</span>
                    ${
                      recording
                        ? html`<span>Press keys</span>`
                        : s.hotkey
                          ? html`<kbd>${formatForDisplay(s.hotkey)}</kbd>`
                          : html`<span>No shortcut</span>`
                    }
                    ${
                      recording
                        ? html`<button
                            type="button"
                            @click=${() => this.listRecorder.cancelRecording()}
                          >
                            Cancel
                          </button>`
                        : html`<button
                            type="button"
                            @click=${() => {
                              // Starting while already recording does nothing,
                              // so a click on another row moves the recording
                              // to that row.
                              this.listRecorder.startRecording()
                              this.editing = s.name
                              this.listStatus = `Recording ${s.name}`
                            }}
                          >
                            Edit
                          </button>`
                    }
                  </li>
                `
              })}
            </ul>
            <p role="status" class="status">${this.listStatus}</p>
          </section>

          <section class="demo-section">
            <h2>Validation</h2>
            <p>
              This recorder rejects a key without a modifier. Press
              <kbd>${formatForDisplay('K')}</kbd>, then
              <kbd>${formatForDisplay('Mod+Shift+K')}</kbd>.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.validationRecorder.startRecording()
                  this.validationStatus = 'Recording'
                }}
              >
                Record
              </button>
            </div>
            <p role="status" class="status">${this.validationStatus}</p>
          </section>

          <section class="demo-section">
            <h2>Conflicts</h2>
            <p>
              This section registers <kbd>${formatForDisplay('Mod+K')}</kbd> for
              a command palette. Record it, or
              <kbd>${formatForDisplay('Mod+S')}</kbd> from the list above, to
              see the conflict. Then record
              <kbd>${formatForDisplay('Mod+J')}</kbd>.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.conflictsRecorder.startRecording()
                  this.conflictsStatus = 'Recording'
                }}
              >
                Record
              </button>
            </div>
            <p role="status" class="status">${this.conflictsStatus}</p>
          </section>

          <section class="demo-section">
            <h2>Record by</h2>
            <p>
              Press <kbd>${formatForDisplay('Shift+[Slash]')}</kbd> with each
              button to compare what gets saved.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.byTypedKey.startRecording()
                  this.recordByStatus = 'Recording'
                }}
              >
                Record what it types
              </button>
              <button
                type="button"
                @click=${() => {
                  this.byPosition.startRecording()
                  this.recordByStatus = 'Recording'
                }}
              >
                Record key position
              </button>
            </div>
            <p role="status" class="status">${this.recordByStatus}</p>
          </section>

          <section class="demo-section">
            <h2>Cancel on blur</h2>
            <p>
              Start recording, switch to another app or tab, then come back and
              press a key combination.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.cancelsOnBlur.startRecording()
                  this.blurStatus = 'Recording'
                }}
              >
                Record (default)
              </button>
              <button
                type="button"
                @click=${() => {
                  this.keepsRecording.startRecording()
                  this.blurStatus = 'Recording'
                }}
              >
                Record (cancelOnBlur: false)
              </button>
            </div>
            <p role="status" class="status">${this.blurStatus}</p>
          </section>

          <section class="demo-section">
            <h2>Record Tab</h2>
            <p>
              Start recording and press <kbd>${formatForDisplay('Tab')}</kbd> or
              <kbd>${formatForDisplay('Shift+Tab')}</kbd>. With recordTab, press
              <kbd>${formatForDisplay('Escape')}</kbd> to cancel.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.tabLeaves.startRecording()
                  this.tabStatus = 'Recording'
                }}
              >
                Record (default)
              </button>
              <button
                type="button"
                @click=${() => {
                  this.tabRecords.startRecording()
                  this.tabStatus = 'Recording'
                }}
              >
                Record (recordTab: true)
              </button>
            </div>
            <p role="status" class="status">${this.tabStatus}</p>
          </section>
        </main>
      </div>
    `
  }
}

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