Skip to content

Alpine Example: CreateHotkey Sequences

import {
  createHotkeysScope,
  getHotkeyManager,
  hotkeysPlugin,
} from '@tanstack/alpine-hotkeys'
import Alpine from 'alpinejs'
import './index.css'

// Gives every hotkeys scope the app's Alpine instance.
Alpine.plugin(hotkeysPlugin)

class App {
  // Owns this component's hotkeys and subscriptions until `destroy()`. To
  // change the default timeout for every sequence it registers, pass
  // `{ hotkey: { timeout: 1500 } }`.
  private hotkeysScope = createHotkeysScope()

  formatForDisplay = this.hotkeysScope.createFormatForDisplay()
  // Every registration on the page, in `.hotkeys`. Sequence views carry
  // `matchedStepCount`, the steps pressed so far.
  registrations = this.hotkeysScope.createHotkeyRegistrations()

  lastCommand = 'none'
  konamiCount = 0
  helloEnabled = true
  helloCount = 0
  saveCount = 0
  renameCount = 0
  runTestsCount = 0

  // 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.
  get pendingKeys() {
    const pending = this.registrations.hotkeys
      .filter((reg) => reg.kind === 'sequence')
      .sort((a, b) => b.matchedStepCount - a.matchedStepCount)
      .at(0)
    return pending?.matchedStepCount
      ? this.formatForDisplay(pending.hotkey.slice(0, pending.matchedStepCount))
      : 'none'
  }

  resetProgress() {
    // 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.
    getHotkeyManager().resetSequenceProgress()
  }

  init() {
    // 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.
    this.hotkeysScope.createHotkey(['G', 'G'], () => {
      this.lastCommand = 'Go to top'
    })
    // A one-step array is a plain chord, the same as `'Shift+G'`.
    this.hotkeysScope.createHotkey(['Shift+G'], () => {
      this.lastCommand = 'Go to bottom'
    })
    this.hotkeysScope.createHotkey(['D', 'D'], () => {
      this.lastCommand = 'Delete line'
    })
    this.hotkeysScope.createHotkey(['Y', 'Y'], () => {
      this.lastCommand = 'Yank line'
    })
    this.hotkeysScope.createHotkey(['D', 'W'], () => {
      this.lastCommand = 'Delete word'
    })
    this.hotkeysScope.createHotkey(['C', 'I', 'W'], () => {
      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.
    this.hotkeysScope.createHotkey(
      ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown'],
      () => {
        this.konamiCount++
      },
      { timeout: 1500 },
    )

    // 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. A plain options object is read once, so a getter keeps
    // `enabled` in step with the checkbox.
    this.hotkeysScope.createHotkey(
      ['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.
    this.hotkeysScope.createHotkey(
      ['Z', 'Z'],
      () => {
        this.saveCount++
      },
      { timeout: 5000 },
    )

    // 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.
    this.hotkeysScope.createHotkey(['F2', 'R'], () => {
      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.
    this.hotkeysScope.createHotkey(['Shift+[KeyR]', 'Shift+[KeyT]'], () => {
      this.runTestsCount++
    })
  }

  destroy() {
    this.hotkeysScope.destroy()
  }
}

Alpine.data('app', () => new App())
Alpine.start()