Skip to content

Alpine Example: CreateHotkeyRecorder Sequences

import {
  createHotkeyRecorder,
  createHotkeysScope,
  hotkeysPlugin,
} from '@tanstack/alpine-hotkeys'
import Alpine from 'alpinejs'
import type { AlpineHotkeyRecorder, Hotkey } from '@tanstack/alpine-hotkeys'
import './index.css'

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

// 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
}

class App {
  // Owns this component's hotkeys and recorders until `destroy()`.
  private hotkeysScope = createHotkeysScope()

  formatForDisplay = this.hotkeysScope.createFormatForDisplay()

  // Recorders are created in `init()`, where their callbacks can change
  // Alpine state through `this`.
  list!: AlpineHotkeyRecorder
  twoSteps!: AlpineHotkeyRecorder
  enterSaves!: AlpineHotkeyRecorder
  enterRecords!: AlpineHotkeyRecorder
  idleTimeout!: AlpineHotkeyRecorder
  validation!: AlpineHotkeyRecorder
  conflicts!: AlpineHotkeyRecorder

  listStatus = 'Not recording'
  editing: string | null = null
  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'] },
  ]
  maxStepsStatus = 'Not recording'
  commitKeysStatus = 'Not recording'
  idleTimeoutStatus = 'Not recording'
  validationStatus = 'Not recording'
  conflictsStatus = 'Not recording'

  isEditing(name: string) {
    return this.editing === name && this.list.isRecording
  }

  edit(name: string) {
    // Starting while already recording does nothing, so a click on another
    // row moves the recording to that row.
    this.list.startRecording()
    this.editing = name
    this.listStatus = `Recording ${name}`
  }

  init() {
    // Shortcut list

    // 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.
    this.list = createHotkeyRecorder(this.hotkeysScope, {
      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
      },
    })

    // The shortcuts are user data held in state, so mapping them into one
    // `createHotkeys` call is the point here. The getter makes the call
    // follow the list. 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.
    this.hotkeysScope.createHotkeys(() =>
      this.shortcuts.map((s) => ({
        hotkey: s.hotkey,
        callback: () => {
          this.listStatus = `Ran ${s.name}`
        },
        options: { meta: { name: s.name } },
      })),
    )

    // Max steps

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

    // Commit keys

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

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

    // Idle timeout

    // 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`.
    this.idleTimeout = createHotkeyRecorder(this.hotkeysScope, {
      maxSteps: Infinity,
      idleTimeoutMs: 1000,
      onRecord: (hotkey) => {
        this.idleTimeoutStatus = `Recorded ${hotkeyText(hotkey)}`
      },
      onCancel: () => {
        this.idleTimeoutStatus = 'Cancelled'
      },
    })

    // Validation

    // `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.
    this.validation = createHotkeyRecorder(this.hotkeysScope, {
      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

    // `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.
    this.conflicts = createHotkeyRecorder(this.hotkeysScope, {
      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'
      },
    })
  }

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

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