Skip to content

Alpine Example: App Hotkeys

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

// A large app can declare hotkeys next to the feature that owns them, then
// spread them into the one object it provides. Each entry keeps its id and
// the kind of its default, so `timeout` stays a sequence option here.
const navigationHotkeys = defineAppHotkeys({
  'nav.inbox': {
    hotkey: ['G', 'I'],
    meta: {
      name: 'Go to inbox',
      description: 'Press G, then I',
      group: 'Navigation',
    },
    // Sequences only. Without it, each key must follow within 1000 ms.
    options: { timeout: 1500 },
  },
})

// Every hotkey in the app, declared once. The keys ('doc.save') are ids:
// saved custom hotkeys refer to them, so keep them stable. The guide puts
// this in its own module that loads with the app shell; it lives here so the
// whole example is in one file.
const appHotkeys = defineAppHotkeys({
  'doc.save': {
    hotkey: 'Mod+S',
    meta: { name: 'Save', description: 'Saves the note', group: 'Document' },
    // Chords only. Without it, holding Mod+S saves again on every key repeat.
    // Mod+S would open the browser's Save dialog; a matched hotkey calls
    // `preventDefault` by default.
    options: { requireReset: true },
  },
  'doc.publish': {
    hotkey: 'Mod+Enter',
    meta: {
      name: 'Publish',
      description: 'Works only while the note has text',
      group: 'Document',
    },
  },
  // `null` declares an action with no default hotkey. It registers nothing
  // until the user assigns one.
  'doc.archive': {
    hotkey: null,
    meta: {
      name: 'Archive',
      description: 'No default hotkey',
      group: 'Document',
    },
  },
  ...navigationHotkeys,
})

// Types `createAppHotkeys()`, `createCustomHotkeys()`, and saved custom
// hotkeys by the ids above, so a misspelled id is a type error.
declare module '@tanstack/alpine-hotkeys' {
  interface Register {
    appHotkeys: typeof appHotkeys
  }
}

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

// Alpine has no provider component, so publish the app hotkeys before Alpine
// starts. `customHotkeys` is the user's saved changes, read once here.
// `onCustomHotkeysChange` gets every change, ready to save. Your app owns
// storage, so swap localStorage for a server without other changes.
provideAppHotkeys(appHotkeys, {
  customHotkeys: JSON.parse(
    localStorage.getItem('tanstack-hotkeys-app-hotkeys') ?? '{}',
  ),
  onCustomHotkeysChange: (customHotkeys) =>
    localStorage.setItem(
      'tanstack-hotkeys-app-hotkeys',
      JSON.stringify(customHotkeys),
    ),
})

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

  formatForDisplay = this.hotkeysScope.createFormatForDisplay()
  // Each id's current hotkey in `.value`, including the user's changes.
  appHotkeys = this.hotkeysScope.createAppHotkeys()
  // Every app hotkey in declaration order, registered or not, in `.value`.
  items = this.hotkeysScope.createAppHotkeyList()
  // The user's changes in `.value`, and functions that change them.
  custom = this.hotkeysScope.createCustomHotkeys()
  // Mounted registrations in `.hotkeys`. A registration's meta includes
  // call-site meta, so Publish shows as "Publish note".
  registrations = this.hotkeysScope.createHotkeyRegistrations()

  lastAction = ''
  published = ''
  result = ''
  message = 'No changes'
  editing: AppHotkeyId | null = null
  recorder!: AlpineHotkeyRecorder

  // Registrations of app hotkeys, for the buttons.
  get appRegistrations() {
    return this.registrations.hotkeys.filter(
      (reg) => reg.options.appHotkeyId !== undefined,
    )
  }

  // `meta.group` values in first-seen order, for the cheat sheet.
  get groups() {
    return [
      ...new Set(this.items.value.map((item) => item.appHotkey.meta?.group)),
    ]
  }

  get customCount() {
    return this.items.value.filter((item) => item.isCustom).length
  }

  nameOf(id: AppHotkeyId) {
    return this.items.value.find((item) => item.appHotkey.id === id)?.appHotkey
      .meta?.name
  }

  // `trigger()` runs the handler and returns whether it ran. It checks only
  // `enabled`.
  run(reg: HotkeyRegistrationView) {
    const name = reg.options.meta?.name
    this.result = reg.trigger() ? `Ran: ${name}` : `Not run: ${name}`
  }

  change(id: AppHotkeyId) {
    this.editing = id
    this.message = `Recording ${this.nameOf(id)}: press keys, then Enter`
    this.recorder.startRecording()
  }

  reset(id: AppHotkeyId) {
    this.custom.resetCustomHotkey(id)
    this.message = `Reset ${this.nameOf(id)}`
  }

  resetAll() {
    this.custom.resetCustomHotkeys()
    this.message = 'Reset all hotkeys'
  }

  init(this: App & Alpine.Magics<App>) {
    // A getter reads `appHotkeys.value`, so the registration moves when the
    // user changes the hotkey below.
    this.hotkeysScope.createHotkey(
      () => this.appHotkeys.value['doc.save'],
      () => {
        this.lastAction = 'Save'
      },
    )
    this.hotkeysScope.createHotkey(
      () => this.appHotkeys.value['nav.inbox'],
      () => {
        this.lastAction = 'Go to inbox'
      },
    )
    // Registers nothing while Archive has no hotkey. Once the user assigns
    // one below, this starts firing without any change here.
    this.hotkeysScope.createHotkey(
      () => this.appHotkeys.value['doc.archive'],
      () => {
        this.lastAction = 'Archive'
      },
    )

    // The default `ignoreInputs: 'auto'` lets Mod shortcuts fire in text
    // fields, so Mod+Enter works while typing in the note. The hotkey calls
    // `preventDefault`, so the textarea gets no new line.
    this.hotkeysScope.createHotkey(
      () => this.appHotkeys.value['doc.publish'],
      () => {
        this.published = (this.$refs.note as HTMLTextAreaElement).value.trim()
      },
      {
        // A function is read on each key press and on `trigger()`, so it
        // sees the textarea's current text without tracking every keystroke.
        enabled: () => !!(this.$refs.note as HTMLTextAreaElement).value.trim(),
        // Merged over the declared meta for this registration only.
        // Registration lists, such as the buttons, show "Publish note"; the
        // cheat sheet keeps the declared "Publish".
        meta: { name: 'Publish note' },
      },
    )

    // One recorder for every row. `maxSteps: Infinity` records a chord or a
    // sequence: press each chord, then Enter. Escape cancels. Backspace with
    // nothing recorded clears the hotkey. App hotkeys don't fire while it
    // records.
    this.recorder = createHotkeyRecorder(this.hotkeysScope, {
      maxSteps: Infinity,
      // Rejecting keeps the recording open with its steps.
      validate: (hotkey, context) => {
        if (!this.editing) return false
        // Pass `context` so a hotkey spelled differently that the same key
        // press fires counts as a conflict.
        const conflicts = this.custom.findConflicts(
          this.editing,
          hotkey,
          context,
        )
        return (
          conflicts.length === 0 ||
          `Not changed: used by ${conflicts[0]?.meta?.name}`
        )
      },
      onReject: (rejection) => {
        this.message = rejection.message ?? 'Not changed: try another hotkey'
      },
      onRecord: (hotkey, context) => {
        if (!this.editing) return
        this.custom.setCustomHotkey(this.editing, hotkey, context)
        this.message = `Changed ${this.nameOf(this.editing)}`
        this.editing = null
      },
      onClear: () => {
        if (!this.editing) return
        this.custom.setCustomHotkey(this.editing, null)
        this.message = `Unassigned ${this.nameOf(this.editing)}`
        this.editing = null
      },
      onCancel: () => {
        this.message = 'Recording cancelled'
        this.editing = null
      },
    })
  }

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

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