Skip to content

Alpine Example: CreateHeldKeys

import { createHotkeysScope, 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()`.
  private hotkeysScope = createHotkeysScope()

  formatForDisplay = this.hotkeysScope.createFormatForDisplay()
  // Held keys in press order, such as ['Shift', 'A'], in `.value`. Updates
  // on every keydown and keyup, and empties when the window loses focus.
  heldKeys = this.hotkeysScope.createHeldKeys()
  // Each held key's physical `event.code`, such as { Shift: 'ShiftLeft' }.
  heldCodes = this.hotkeysScope.createHeldKeyCodes()

  // True while the user holds Mod, and the Mod+S below can fire. The hint
  // registers nothing: it reads the held keys and the registrations.
  saveHint = this.hotkeysScope.createHotkeyHint('Mod+S')
  // False while Bold is disabled, even with Mod held, because no enabled
  // registration of Mod+B can fire.
  boldHint = this.hotkeysScope.createHotkeyHint('Mod+B')
  // True while the user holds Mod, Shift, or both. Holding a modifier the
  // hotkey doesn't use, such as Alt, hides it.
  exportHint = this.hotkeysScope.createHotkeyHint('Mod+Shift+E')
  // With `exact: true`, only Mod and Shift held together show the hint.
  // Without it, Mod or Shift alone would show it, as for Export.
  archiveHint = this.hotkeysScope.createHotkeyHint('Mod+Shift+A', {
    exact: true,
  })

  history: Array<string> = []
  lastAction = 'none'
  boldEnabled = true
  mostHeld: Array<string> = []

  get shownHints() {
    const shown = [
      this.saveHint.value && 'Save',
      this.boldHint.value && 'Bold',
      this.exportHint.value && 'Export',
      this.archiveHint.value && 'Archive',
    ].filter(Boolean)
    return shown.length > 0
      ? `Hints shown: ${shown.join(', ')}`
      : 'Hints shown: none'
  }

  init(this: App & Alpine.Magics<App>) {
    // Once every key is released, records the most keys held at once, such
    // as 'Shift + Control + A', and keeps the last 10.
    this.$watch('heldKeys.value', (keys: Array<string>) => {
      if (keys.length > this.mostHeld.length) this.mostHeld = keys
      if (keys.length > 0 || this.mostHeld.length === 0) return
      const combination = this.mostHeld.join(' + ')
      this.mostHeld = []
      this.history = [...this.history.slice(-9), combination]
    })

    // Mod+S would open the browser's Save dialog. A matched hotkey calls
    // `preventDefault` by default, so the page handles it instead.
    this.hotkeysScope.createHotkey('Mod+S', () => {
      this.lastAction = 'Save'
    })
    // While `enabled` is false, Mod+B doesn't fire, and its hint stays
    // hidden. A getter keeps the option in step with the checkbox.
    this.hotkeysScope.createHotkey(
      'Mod+B',
      () => {
        this.lastAction = 'Bold'
      },
      () => ({ enabled: this.boldEnabled }),
    )
    this.hotkeysScope.createHotkey('Mod+Shift+E', () => {
      this.lastAction = 'Export'
    })
    this.hotkeysScope.createHotkey('Mod+Shift+A', () => {
      this.lastAction = 'Archive'
    })
  }

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

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