Skip to content

Alpine Example: CreateHotkey

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 until `destroy()`. Pass default options,
  // such as `{ hotkey: { requireReset: true } }`, to set defaults for every
  // hotkey it registers. Each call's own options override them.
  private hotkeysScope = createHotkeysScope()

  formatForDisplay = this.hotkeysScope.createFormatForDisplay()

  lastBasic = 'none'
  resetCount = 0
  previewShown = false
  stateEnabled = true
  enabledCounts = { e: 0, g: 0 }
  targetCounts = { panel: 0, drawer: 0 }
  drawerOpen = false
  drawer: HTMLElement | null = null
  lastInputs = 'none'
  lastPrevent = 'none'
  stopPanel = true
  stopCounts = { panel: 0, page: 0 }
  captureCounts = { bubble: 0, capture: 0 }
  handledCounts = { b: 0, i: 0 }
  duplicateCounts = { y: 0, u: 0 }

  toggleDrawer() {
    this.drawerOpen = !this.drawerOpen
    // x-if removes the drawer when it closes. Clearing the element here
    // unregisters its hotkey.
    if (!this.drawerOpen) this.drawer = null
  }

  init(this: App & Alpine.Magics<App>) {
    // Chords as strings and objects

    // `hotkey` is the chord as registered, with `Mod` kept. `parsedChord` has
    // `Mod` resolved for this platform: Meta on macOS, Control elsewhere.
    // Mod+S would open the browser's Save dialog. A matched hotkey calls
    // `preventDefault` by default, so the dialog stays closed.
    // `meta` doesn't change matching. The devtools and cheat sheets read it.
    this.hotkeysScope.createHotkey(
      'Mod+S',
      (_event, { hotkey, parsedChord }) => {
        this.lastBasic = `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`
      },
      { meta: { name: 'Save', description: 'Save the document' } },
    )

    // Function keys, arrow keys, and named keys use their `event.key` names.
    // To match a key by position instead, write its code: 'Mod+[KeyS]'.
    this.hotkeysScope.createHotkey('F2', (_event, { hotkey, parsedChord }) => {
      this.lastBasic = `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`
    })
    this.hotkeysScope.createHotkey(
      'Alt+ArrowUp',
      (_event, { hotkey, parsedChord }) => {
        this.lastBasic = `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`
      },
    )
    this.hotkeysScope.createHotkey(
      'Escape',
      (_event, { hotkey, parsedChord }) => {
        this.lastBasic = `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`
      },
    )

    // The same chord as an object, for chords built from data such as
    // modifier checkboxes. `hotkey` reports it as the string 'Mod+Shift+S'.
    this.hotkeysScope.createHotkey(
      { key: 'S', mod: true, shift: true },
      (_event, { hotkey, parsedChord }) => {
        this.lastBasic = `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`
      },
    )

    // Fire once while held

    // Chords only. Without `requireReset`, holding Mod+K fires again on every
    // key repeat. With it, Mod+K fires once until you release a key.
    this.hotkeysScope.createHotkey(
      'Mod+K',
      () => {
        this.resetCount++
      },
      { requireReset: true },
    )

    // Fire on key release

    // Hold Mod+P to show the preview. The keydown hotkey shows it, and the
    // keyup hotkey hides it when you release P or Mod. The two don't conflict
    // because their `eventType` differs. A keyup hotkey still calls
    // `preventDefault` on the keydown, so the print dialog doesn't open.
    this.hotkeysScope.createHotkey('Mod+P', () => {
      this.previewShown = true
    })
    this.hotkeysScope.createHotkey(
      'Mod+P',
      () => {
        this.previewShown = false
      },
      { eventType: 'keyup' },
    )

    // Turn hotkeys on and off

    // A plain options object is read once, so pass a getter for options that
    // follow Alpine state. A disabled hotkey stays registered and visible in
    // the devtools. It doesn't call `preventDefault`, so the browser handles
    // Mod+E.
    this.hotkeysScope.createHotkey(
      'Mod+E',
      () => {
        this.enabledCounts.e++
      },
      () => ({ enabled: this.stateEnabled }),
    )

    // A function is read on each key press, for state that lives outside
    // Alpine. This one reads a checkbox that isn't bound to Alpine state.
    // Keep the function cheap: it runs on every key press.
    this.hotkeysScope.createHotkey(
      'Mod+G',
      () => {
        this.enabledCounts.g++
      },
      {
        // `$refs` types every element as HTMLElement, so name the input type.
        enabled: () => (this.$refs.getterCheckbox as HTMLInputElement).checked,
      },
    )

    // Listen on one element

    // An element only gets key events while it or something inside it has
    // focus, so the panel has `tabindex="0"`. Enter does nothing elsewhere.
    // A getter lets the hotkey find the element after Alpine creates it.
    this.hotkeysScope.createHotkey(
      'Enter',
      () => {
        this.targetCounts.panel++
      },
      () => ({ target: this.$refs.panel }),
    )

    // The drawer is added later by x-if, so `$refs` doesn't have it when
    // `init()` runs. Its `x-init` stores it in `drawer` instead, and the
    // getter runs again when `drawer` changes. While `drawer` is null,
    // nothing is registered. Each target gets its own Enter, so these two
    // don't conflict.
    this.hotkeysScope.createHotkey(
      'Enter',
      () => {
        this.targetCounts.drawer++
      },
      () => ({ target: this.drawer }),
    )

    // Typing in text fields

    // The default `ignoreInputs: 'auto'` decides from the hotkey. A key that
    // types or edits text, such as N, Shift+N, Alt+N, or an arrow key, is
    // skipped while a text field has focus, so N types into the field.
    this.hotkeysScope.createHotkey('N', (_event, { hotkey }) => {
      this.lastInputs = hotkey
    })

    // With 'auto', Control and Meta chords, Escape, and function keys fire in
    // text fields too, because they type nothing.
    this.hotkeysScope.createHotkey('Mod+Enter', (_event, { hotkey }) => {
      this.lastInputs = hotkey
    })

    // `true` skips text fields for every hotkey. Mod+A then selects the
    // field's text, and selects nothing on the rest of the page.
    this.hotkeysScope.createHotkey(
      'Mod+A',
      (_event, { hotkey }) => {
        this.lastInputs = hotkey
      },
      { ignoreInputs: true },
    )

    // `false` fires in text fields too. 'auto' would skip Shift+Enter there.
    this.hotkeysScope.createHotkey(
      'Shift+Enter',
      (_event, { hotkey }) => {
        this.lastInputs = hotkey
      },
      { ignoreInputs: false },
    )

    // The browser's default action

    // These hotkeys listen on the text field. A hotkey targeted at a field
    // always gets its keys, whatever `ignoreInputs` says. By default a
    // matched hotkey calls `preventDefault`, so 1 doesn't type.
    this.hotkeysScope.createHotkey(
      '1',
      (_event, { hotkey }) => {
        this.lastPrevent = hotkey
      },
      () => ({ target: this.$refs.digits }),
    )

    // `false` lets the browser act too, so 2 fires the hotkey and types.
    this.hotkeysScope.createHotkey(
      '2',
      (_event, { hotkey }) => {
        this.lastPrevent = hotkey
      },
      () => ({ target: this.$refs.digits, preventDefault: false }),
    )

    // A disabled hotkey normally leaves the key to the browser. `'always'`
    // keeps calling `preventDefault` while the hotkey is disabled, so 3
    // doesn't type and the callback doesn't run.
    this.hotkeysScope.createHotkey(
      '3',
      (_event, { hotkey }) => {
        this.lastPrevent = hotkey
      },
      () => ({
        target: this.$refs.digits,
        enabled: false,
        preventDefault: 'always',
      }),
    )

    // Stop outer hotkeys

    // With focus inside the panel, its hotkey runs before the page's hotkey
    // for the same key. `stopPropagation: true`, the default, stops the event
    // there, so the page's Mod+D doesn't fire. With `false`, both fire.
    this.hotkeysScope.createHotkey(
      'Mod+D',
      () => {
        this.stopCounts.panel++
      },
      () => ({
        target: this.$refs.stopPanelArea,
        stopPropagation: this.stopPanel,
      }),
    )
    this.hotkeysScope.createHotkey('Mod+D', () => {
      this.stopCounts.page++
    })

    // Run before a widget's own handler

    // Hotkeys listen in the bubble phase, after the focused element's own
    // handlers. The widget calls `stopPropagation` on every key, so
    // Mod+ArrowUp never reaches the page while the widget has focus.
    this.hotkeysScope.createHotkey('Mod+ArrowUp', () => {
      this.captureCounts.bubble++
    })

    // `capture: true` runs the hotkey on the way down, before the widget's
    // handler. With the default `stopPropagation: true`, the widget then
    // doesn't see Mod+ArrowDown at all.
    this.hotkeysScope.createHotkey(
      'Mod+ArrowDown',
      () => {
        this.captureCounts.capture++
      },
      { capture: true },
    )

    // Keys another listener already handled

    // The editor calls `preventDefault` on its Control and Meta chords, as
    // rich text editors do for Mod+B. With `ignoreDefaultPrevented: true`,
    // the hotkey skips a key press that another listener already prevented.
    this.hotkeysScope.createHotkey(
      'Mod+B',
      () => {
        this.handledCounts.b++
      },
      { ignoreDefaultPrevented: true },
    )

    // By default a hotkey fires even when the key was already prevented.
    this.hotkeysScope.createHotkey('Mod+I', () => {
      this.handledCounts.i++
    })

    // Duplicate hotkeys

    // Two registrations of the same hotkey on the same target both run.
    // `conflictBehavior` is checked when the second one registers, so set it
    // on each registration that may register second. 'allow' registers both
    // silently.
    this.hotkeysScope.createHotkey(
      'Mod+Y',
      () => {
        this.duplicateCounts.y++
      },
      { conflictBehavior: 'allow' },
    )
    this.hotkeysScope.createHotkey(
      'Mod+Y',
      () => {
        this.duplicateCounts.y++
      },
      { conflictBehavior: 'allow' },
    )

    // The default, 'warn', also registers both, and logs
    // "[hotkeys] 'Mod+U' is already registered" in development. This example
    // triggers that warning on purpose. 'error' throws when the second one
    // registers instead.
    this.hotkeysScope.createHotkey('Mod+U', () => {
      this.duplicateCounts.u++
    })
    this.hotkeysScope.createHotkey('Mod+U', () => {
      this.duplicateCounts.u++
    })
  }

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

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