Skip to content

Alpine Example: CreateHotkeyRecorder

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

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

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<HotkeyChord>
  validation!: AlpineHotkeyRecorder<HotkeyChord>
  conflicts!: AlpineHotkeyRecorder<HotkeyChord>
  byTypedKey!: AlpineHotkeyRecorder<HotkeyChord>
  byPosition!: AlpineHotkeyRecorder<HotkeyChord>
  cancelsOnBlur!: AlpineHotkeyRecorder<HotkeyChord>
  keepsRecording!: AlpineHotkeyRecorder<HotkeyChord>
  tabLeaves!: AlpineHotkeyRecorder<HotkeyChord>
  tabRecords!: AlpineHotkeyRecorder<HotkeyChord>

  listStatus = 'Not recording'
  editing: string | null = null
  shortcuts: Array<{ name: string; hotkey: HotkeyChord | null }> = [
    { name: 'Save', hotkey: 'Mod+S' },
    { name: 'Open', hotkey: 'Mod+O' },
    { name: 'Toggle sidebar', hotkey: 'Mod+B' },
  ]
  validationStatus = 'Not recording'
  conflictsStatus = 'Not recording'
  recordByStatus = 'Not recording'
  blurStatus = 'Not recording'
  tabStatus = '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

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

    // 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, and 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.
    this.hotkeysScope.createHotkeys(() =>
      this.shortcuts.map((s) => ({
        hotkey: s.hotkey,
        callback: () => {
          this.listStatus = `Ran ${s.name}`
        },
        options: { meta: { name: s.name } },
      })),
    )

    // Validation

    // Return true to accept, or a message to reject. A rejected chord keeps
    // the recorder listening for another one, and `onReject` gets the
    // message.
    this.validation = createHotkeyRecorder(this.hotkeysScope, {
      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

    this.hotkeysScope.createHotkey(
      'Mod+K',
      () => {
        this.conflictsStatus = 'Ran Command palette'
      },
      { meta: { name: '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.
    this.conflicts = createHotkeyRecorder(this.hotkeysScope, {
      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

    // 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 `ß`.)
    this.byTypedKey = createHotkeyRecorder(this.hotkeysScope, {
      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.
    this.byPosition = createHotkeyRecorder(this.hotkeysScope, {
      recordBy: 'code',
      onRecord: (hotkey) => {
        this.recordByStatus = `Recorded ${hotkey}`
      },
      onCancel: () => {
        this.recordByStatus = 'Cancelled'
      },
    })

    // Cancel on blur

    // 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.
    this.cancelsOnBlur = createHotkeyRecorder(this.hotkeysScope, {
      onRecord: (hotkey) => {
        this.blurStatus = `Recorded ${hotkey}`
      },
      onCancel: () => {
        this.blurStatus = 'Cancelled'
      },
    })

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

    // Record Tab

    // By default, Tab and Shift+Tab cancel recording and move focus as usual,
    // so a keyboard user can leave the recorder.
    this.tabLeaves = createHotkeyRecorder(this.hotkeysScope, {
      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 on the page
    // does.
    this.tabRecords = createHotkeyRecorder(this.hotkeysScope, {
      recordTab: true,
      onRecord: (hotkey) => {
        this.tabStatus = `Recorded ${hotkey}`
      },
      onCancel: () => {
        this.tabStatus = 'Cancelled'
      },
    })
  }

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

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