Skip to content

Lit Example: Hotkey Sequences

import {
  FormatForDisplayController,
  HotkeyController,
  HotkeyRegistrationsController,
  getHotkeyManager,
  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'

// Lit has no provider for default options, so there is no global `timeout`.
// Set it on each sequence that needs a different one, as the Konami code
// below does.
@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)
  private registrations = new HotkeyRegistrationsController(this)

  @state() private lastCommand = 'none'
  @state() private konamiCount = 0
  @state() private helloEnabled = true
  @state() private helloCount = 0
  @state() private saveCount = 0
  @state() private renameCount = 0
  @state() private runTestsCount = 0

  // An array is a sequence: press each step in order, within 1 second of the
  // step before it. `['D', 'D']` and `['D', 'W']` share a first step, and the
  // second key decides which one fires.
  @hotkey(['G', 'G'])
  goToTop() {
    this.lastCommand = 'Go to top'
  }

  // A one-step array is a plain chord, the same as `'Shift+G'`.
  @hotkey(['Shift+G'])
  goToBottom() {
    this.lastCommand = 'Go to bottom'
  }

  @hotkey(['D', 'D'])
  deleteLine() {
    this.lastCommand = 'Delete line'
  }

  @hotkey(['Y', 'Y'])
  yankLine() {
    this.lastCommand = 'Yank line'
  }

  @hotkey(['D', 'W'])
  deleteWord() {
    this.lastCommand = 'Delete word'
  }

  @hotkey(['C', 'I', 'W'])
  changeInnerWord() {
    this.lastCommand = 'Change inner word'
  }

  // Sequences only: allow 1.5 seconds between steps instead of the default
  // 1 second. A longer gap clears the progress, and the next ArrowUp starts
  // over.
  @hotkey(['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown'], { timeout: 1500 })
  countKonami() {
    this.konamiCount++
  }

  // Decorator options are fixed when the class is defined, so a sequence
  // whose options read element state uses `HotkeyController` with an options
  // function. The controller calls it again after each update.
  // While `enabled` is false, the sequence stays registered but doesn't
  // advance or fire, and H E L L O reach the page as plain keys. A sequence
  // of letters counts as a character-key shortcut, so give users a way to
  // turn it off.
  private hello = new HotkeyController(
    this,
    ['H', 'E', 'L', 'L', 'O'],
    () => this.helloCount++,
    () => ({ enabled: this.helloEnabled }),
  )

  // A 5 second timeout leaves time to click Reset progress between the two
  // presses of Z.
  @hotkey(['Z', 'Z'], { timeout: 5000 })
  saveAndQuit() {
    this.saveCount++
  }

  // By default, a sequence whose first step types a character, such as
  // `['G', 'G']`, doesn't advance while focus is in a text field.
  // A sequence that starts with F2 still fires there, and the R that
  // finishes it doesn't type into the field.
  @hotkey(['F2', 'R'])
  rename() {
    this.renameCount++
  }

  // Each step is a chord. Shift can stay held between steps, and a Shift
  // press on its own doesn't reset progress. `[KeyR]` and `[KeyT]` name
  // physical keys, so the sequence fires on those positions on any layout.
  @hotkey(['Shift+[KeyR]', 'Shift+[KeyT]'])
  runTests() {
    this.runTestsCount++
  }

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

    // Every sequence's progress, from its registration. Show the one with the
    // most steps matched. matchedStepCount is 0 when a sequence is idle, and
    // resets on completion, a wrong key, or a timeout.
    const pending = this.registrations.hotkeys
      .filter((reg) => reg.kind === 'sequence')
      .sort((a, b) => b.matchedStepCount - a.matchedStepCount)
      .at(0)
    const pendingKeys = pending?.matchedStepCount
      ? formatForDisplay(pending.hotkey.slice(0, pending.matchedStepCount))
      : 'none'

    return html`
      <div class="app">
        <header>
          <h1>Sequences with @hotkey</h1>
          <p>
            Pass an array of chords to @hotkey to register a sequence, such as G
            then G in Vim. Each key must follow the previous one within the
            timeout.
          </p>
        </header>

        <main>
          <section class="demo-section">
            <h2>Vim-style commands</h2>
            <table class="sequence-table">
              <thead>
                <tr>
                  <th>Keys</th>
                  <th>Command</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td><kbd>${formatForDisplay(['G', 'G'])}</kbd></td>
                  <td>Go to top</td>
                </tr>
                <tr>
                  <td><kbd>${formatForDisplay('Shift+G')}</kbd></td>
                  <td>Go to bottom</td>
                </tr>
                <tr>
                  <td><kbd>${formatForDisplay(['D', 'D'])}</kbd></td>
                  <td>Delete line</td>
                </tr>
                <tr>
                  <td><kbd>${formatForDisplay(['Y', 'Y'])}</kbd></td>
                  <td>Yank line</td>
                </tr>
                <tr>
                  <td><kbd>${formatForDisplay(['D', 'W'])}</kbd></td>
                  <td>Delete word</td>
                </tr>
                <tr>
                  <td><kbd>${formatForDisplay(['C', 'I', 'W'])}</kbd></td>
                  <td>Change inner word</td>
                </tr>
              </tbody>
            </table>
            <p role="status">Last command: ${this.lastCommand}</p>
          </section>

          <section class="demo-section">
            <h2>Set the time between steps</h2>
            <p>
              Press
              <kbd
                >${formatForDisplay([
                  'ArrowUp',
                  'ArrowUp',
                  'ArrowDown',
                  'ArrowDown',
                ])}</kbd
              >
              with up to 1.5 seconds between keys.
            </p>
            <p role="status">Konami code: ${this.konamiCount}</p>
          </section>

          <section class="demo-section">
            <h2>Turn a sequence on and off</h2>
            <label>
              <input
                type="checkbox"
                .checked=${this.helloEnabled}
                @change=${(event: Event) =>
                  (this.helloEnabled = (
                    event.target as HTMLInputElement
                  ).checked)}
              />
              Enable the hello sequence
            </label>
            <p>
              Type <kbd>${formatForDisplay(['H', 'E', 'L', 'L', 'O'])}</kbd>.
            </p>
            <p role="status">Hello: ${this.helloCount}</p>
          </section>

          <section class="demo-section">
            <h2>Show and reset progress</h2>
            <p>
              Press <kbd>${formatForDisplay('Z')}</kbd> once, then reset before
              the second <kbd>${formatForDisplay('Z')}</kbd>. Any other sequence
              in progress shows here too.
            </p>
            <!-- A click isn't a key press, so it can't cancel a sequence the
                 way a wrong key does. resetSequenceProgress clears every
                 sequence in progress. -->
            <button
              type="button"
              @click=${() => getHotkeyManager().resetSequenceProgress()}
            >
              Reset progress
            </button>
            <p role="status">
              Pending: ${pendingKeys}, Save and quit: ${this.saveCount}
            </p>
          </section>

          <section class="demo-section">
            <h2>Typing in a text field</h2>
            <p>
              Type <kbd>${formatForDisplay(['G', 'G'])}</kbd> in the field: it
              types text and doesn't go to top. Press
              <kbd>${formatForDisplay(['F2', 'R'])}</kbd> in the field to
              rename.
            </p>
            <label> Notes <input type="text" class="demo-input" /> </label>
            <p role="status">Rename: ${this.renameCount}</p>
          </section>

          <section class="demo-section">
            <h2>Hold Shift between steps</h2>
            <p>
              Press
              <kbd>${formatForDisplay(['Shift+[KeyR]', 'Shift+[KeyT]'])}</kbd>.
              Shift can stay down between the two keys.
            </p>
            <p role="status">Run tests: ${this.runTestsCount}</p>
          </section>
        </main>
      </div>
    `
  }
}

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