Skip to content

Lit Example: Hotkey Recorder Sequences

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

// A recorded hotkey as text: `Mod+S` for a chord, `G H` for a sequence. A
// sequence is an array of chords, such as `['G', 'H']`.
function hotkeyText(hotkey: Hotkey) {
  return Array.isArray(hotkey) ? hotkey.join(' ') : hotkey
}

@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: Hotkey | null }> = [
    { name: 'Save', hotkey: 'Mod+S' },
    { name: 'Go to inbox', hotkey: ['G', 'I'] },
    { name: 'Go to settings', hotkey: ['G', 'S'] },
  ]

  // With `maxSteps: Infinity`, each chord adds a step and Enter saves. One
  // step saves as a chord string such as 'Mod+S'; two or more save as a
  // sequence such as ['G', 'H']. Backspace removes the last step, and on an
  // empty recording calls `onClear`. Escape cancels. The callbacks read
  // `this.editing` when they run.
  private listRecorder = new HotkeyRecorderController(this, {
    maxSteps: Infinity,
    onRecord: (hotkey) => {
      this.shortcuts = this.shortcuts.map((s) =>
        s.name === this.editing ? { ...s, hotkey } : s,
      )
      this.listStatus = `${this.editing} is now ${hotkeyText(hotkey)}`
      this.editing = null
    },
    onCancel: () => {
      this.listStatus = `${this.editing} unchanged`
      this.editing = null
    },
    // The recorder only reports the clear; 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.
    // Chords and sequences register the same way, and a null hotkey
    // registers nothing. Mod+S would open the browser's Save dialog; a
    // matched hotkey calls `preventDefault` by default. While any recorder is
    // recording, these hotkeys pause.
    for (const { name } of this.shortcuts) {
      new HotkeyController(
        this,
        () => this.shortcuts.find((s) => s.name === name)?.hotkey,
        () => (this.listStatus = `Ran ${name}`),
        { meta: { name } },
      )
    }
  }

  // Max steps
  @state() private maxStepsStatus = 'Not recording'

  // Recording saves by itself when it reaches `maxSteps`, here the second
  // chord. Enter still saves a single chord before that.
  private maxStepsRecorder = new HotkeyRecorderController(this, {
    maxSteps: 2,
    onRecord: (hotkey) =>
      (this.maxStepsStatus = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.maxStepsStatus = 'Cancelled'),
  })

  // Commit keys
  @state() private commitStatus = 'Not recording'

  // The default, `commitKeys: 'enter'`: plain Enter saves the steps.
  private enterSaves = new HotkeyRecorderController(this, {
    maxSteps: Infinity,
    commitKeys: 'enter',
    onRecord: (hotkey) =>
      (this.commitStatus = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.commitStatus = 'Cancelled'),
  })

  // With `commitKeys: 'none'`, Enter is recorded as a step, so a sequence
  // can end in Enter. Save with `commitRecording()`, `idleTimeoutMs`, or
  // `maxSteps` instead.
  private enterRecords = new HotkeyRecorderController(this, {
    maxSteps: Infinity,
    commitKeys: 'none',
    onRecord: (hotkey) =>
      (this.commitStatus = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.commitStatus = 'Cancelled'),
  })

  // Idle timeout
  @state() private idleStatus = 'Not recording'

  // Saves one second after the last chord, so the user doesn't need Enter.
  // Each new chord restarts the wait. Without it, a recording waits for
  // Enter or `maxSteps`.
  private idleRecorder = new HotkeyRecorderController(this, {
    maxSteps: Infinity,
    idleTimeoutMs: 1000,
    onRecord: (hotkey) => (this.idleStatus = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.idleStatus = 'Cancelled'),
  })

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

  // `validate` runs when the recording saves. Check `context.kind` before
  // reading `parsedChord` (one step) or `parsedSequence` (two or more). A
  // rejected recording keeps its steps, so the user can add a chord or press
  // Backspace instead of starting over.
  private validationRecorder = new HotkeyRecorderController(this, {
    maxSteps: Infinity,
    validate: (_hotkey, context) =>
      context.kind === 'sequence' ||
      context.parsedChord.modifiers.length > 0 ||
      'A single chord needs a modifier.',
    onReject: ({ reason, message }) =>
      (this.validationStatus = message
        ? `Rejected: ${message}`
        : `Rejected (${reason})`),
    onRecord: (hotkey) =>
      (this.validationStatus = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.validationStatus = 'Cancelled'),
  })

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

  // `detectConflicts` rejects a recording that a registered hotkey already
  // uses, including prefixes: a chord conflicts with a sequence that starts
  // with it, so `G` conflicts with G I. A sequence conflicts with a chord
  // equal to its first step. G H and G I don't conflict.
  private conflictsRecorder = new HotkeyRecorderController(this, {
    maxSteps: Infinity,
    detectConflicts: true,
    onReject: ({ reason, hotkey, conflicts }) =>
      (this.conflictsStatus =
        reason === 'conflict' && hotkey
          ? `Rejected: ${hotkeyText(hotkey)} is used by ${conflicts
              ?.map((c) => c.registration.options.meta?.name)
              .join(', ')}`
          : `Rejected (${reason})`),
    onRecord: (hotkey) =>
      (this.conflictsStatus = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.conflictsStatus = 'Cancelled'),
  })

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

    return html`
      <div class="app">
        <header>
          <h1>Recording Sequences</h1>
          <p>
            With <code>maxSteps</code> above 1,
            <code>HotkeyRecorderController</code> records several chords in a
            row, such as G then I. Each section shows one recorder option.
          </p>
        </header>

        <main>
          <section class="demo-section">
            <h2>Shortcut list</h2>
            <p>
              Click Edit, press each chord in order, then press Enter. Backspace
              removes the last chord, or clears the shortcut when none are left.
              Escape cancels.
            </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
                        ? this.listRecorder.steps.length > 0
                          ? html`<kbd
                              >${formatForDisplay(this.listRecorder.steps)}</kbd
                            >`
                          : 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>Max steps</h2>
            <p>
              Press <kbd>${formatForDisplay('G')}</kbd>, then
              <kbd>${formatForDisplay('H')}</kbd>. Recording ends at the second
              chord without Enter.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.maxStepsRecorder.startRecording()
                  this.maxStepsStatus = 'Recording'
                }}
              >
                Record
              </button>
            </div>
            <p role="status" class="status">${this.maxStepsStatus}</p>
          </section>

          <section class="demo-section">
            <h2>Commit keys</h2>
            <p>
              Press <kbd>${formatForDisplay('G')}</kbd>, then
              <kbd>${formatForDisplay('Enter')}</kbd> with each button. With
              commitKeys: 'none', click Done to save.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.enterSaves.startRecording()
                  this.commitStatus = 'Recording'
                }}
              >
                Record (commitKeys: 'enter')
              </button>
              <button
                type="button"
                @click=${() => {
                  this.enterRecords.startRecording()
                  this.commitStatus = 'Recording'
                }}
              >
                Record (commitKeys: 'none')
              </button>
              <button
                type="button"
                ?disabled=${this.enterRecords.steps.length === 0}
                @click=${() => this.enterRecords.commitRecording()}
              >
                Done
              </button>
            </div>
            ${
              this.enterRecords.steps.length > 0
                ? html`<p>
                    Steps:
                    <kbd>${formatForDisplay(this.enterRecords.steps)}</kbd>
                  </p>`
                : nothing
            }
            <p role="status" class="status">${this.commitStatus}</p>
          </section>

          <section class="demo-section">
            <h2>Idle timeout</h2>
            <p>
              Press <kbd>${formatForDisplay('G')}</kbd>, then
              <kbd>${formatForDisplay('H')}</kbd>, and wait one second.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.idleRecorder.startRecording()
                  this.idleStatus = 'Recording'
                }}
              >
                Record
              </button>
            </div>
            ${
              this.idleRecorder.steps.length > 0
                ? html`<p>
                    Steps:
                    <kbd>${formatForDisplay(this.idleRecorder.steps)}</kbd>
                  </p>`
                : nothing
            }
            <p role="status" class="status">${this.idleStatus}</p>
          </section>

          <section class="demo-section">
            <h2>Validation</h2>
            <p>
              Press <kbd>${formatForDisplay('G')}</kbd>, then
              <kbd>${formatForDisplay('Enter')}</kbd> to see the rejection. Then
              press <kbd>${formatForDisplay('H')}</kbd> and
              <kbd>${formatForDisplay('Enter')}</kbd>.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.validationRecorder.startRecording()
                  this.validationStatus = 'Recording'
                }}
              >
                Record
              </button>
            </div>
            ${
              this.validationRecorder.steps.length > 0
                ? html`<p>
                    Steps:
                    <kbd
                      >${formatForDisplay(this.validationRecorder.steps)}</kbd
                    >
                  </p>`
                : nothing
            }
            <p role="status" class="status">${this.validationStatus}</p>
          </section>

          <section class="demo-section">
            <h2>Conflicts</h2>
            <p>
              Record <kbd>${formatForDisplay('G')}</kbd> alone, or
              <kbd>${formatForDisplay(['G', 'I'])}</kbd>, to conflict with the
              list above. Then record
              <kbd>${formatForDisplay(['G', 'H'])}</kbd>.
            </p>
            <div class="buttons">
              <button
                type="button"
                @click=${() => {
                  this.conflictsRecorder.startRecording()
                  this.conflictsStatus = 'Recording'
                }}
              >
                Record
              </button>
            </div>
            ${
              this.conflictsRecorder.steps.length > 0
                ? html`<p>
                    Steps:
                    <kbd>${formatForDisplay(this.conflictsRecorder.steps)}</kbd>
                  </p>`
                : nothing
            }
            <p role="status" class="status">${this.conflictsStatus}</p>
          </section>
        </main>
      </div>
    `
  }
}

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