Skip to content

Alpine Example: Accessibility

import {
  createHotkeysScope,
  getHotkeyManager,
  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()
  private resumeCharacterKeys: (() => void) | undefined

  // Formats a hotkey for `aria-keyshortcuts`: `Meta+S` on macOS and
  // `Control+S` elsewhere. It returns undefined while the hotkey can't fire,
  // and for a sequence, so `:aria-keyshortcuts` leaves the attribute off.
  formatForAria = this.hotkeysScope.createFormatForAria()
  formatForDisplay = this.hotkeysScope.createFormatForDisplay()
  // `characterKeysSuspended` is true while anything suspends character keys.
  // Use it to show whether single-key shortcuts work right now, and bind the
  // checkbox to the setting.
  scopes = this.hotkeysScope.createHotkeyScopesState()
  // True while the user holds Alt, the modifier of an active Alt+A hotkey.
  // It only reports state and registers nothing.
  archiveHint = this.hotkeysScope.createHotkeyHint('Alt+[KeyA]')

  // The user's setting. A real app would save it with the user's preferences.
  singleKeyShortcuts = true
  lastAction = 'none'
  likes = 0
  bookmarks = 0
  selected = 1
  archived = 0
  previousPage = 0
  dialogOpen = false
  escapes = 0

  // While suspended, document-level shortcuts made only of keys that type a
  // character, such as `L` or `['G', 'I']`, stop firing across the whole
  // app. Shortcuts with Control, Alt, or Meta, keys that type nothing, such
  // as Escape, and hotkeys with an element `target` keep working.
  setSingleKeyShortcuts(on: boolean) {
    this.singleKeyShortcuts = on
    if (on) {
      this.resumeCharacterKeys?.()
      this.resumeCharacterKeys = undefined
    } else {
      // Returns a function that resumes them. Suspensions are counted, so
      // keep it and call it once.
      this.resumeCharacterKeys ??= getHotkeyManager().suspendCharacterKeys()
    }
  }

  init(this: App & Alpine.Magics<App>) {
    // Mod+S would open the browser's Save dialog. A matched hotkey calls
    // `preventDefault` by default.
    this.hotkeysScope.createHotkey('Mod+S', () => {
      this.lastAction = 'Save'
    })
    this.hotkeysScope.createHotkey(['G', 'I'], () => {
      this.lastAction = 'Go to inbox'
    })

    // L types a character, so it stops while character keys are suspended.
    this.hotkeysScope.createHotkey('L', () => {
      this.likes++
    })
    // Alt keeps this one working. The physical code `[KeyB]` matches the
    // key, because Alt+B types a character such as ∫ on macOS.
    this.hotkeysScope.createHotkey('Alt+[KeyB]', () => {
      this.bookmarks++
    })

    // With an element `target`, J and K fire only while focus is inside the
    // list, which WCAG 2.1.4 allows for single-key shortcuts. They keep
    // working while single-key shortcuts are off. Without `target`, they
    // would fire anywhere on the page. Pass options as a getter, so `$refs`
    // is read after Alpine creates the component.
    this.hotkeysScope.createHotkey(
      'J',
      () => {
        this.selected = Math.min(this.selected + 1, 3)
      },
      () => ({ target: this.$refs.list }),
    )
    this.hotkeysScope.createHotkey(
      'K',
      () => {
        this.selected = Math.max(this.selected - 1, 1)
      },
      () => ({ target: this.$refs.list }),
    )

    // The physical code `[KeyA]` matches the key, because Alt+A types å on
    // macOS.
    this.hotkeysScope.createHotkey('Alt+[KeyA]', () => {
      this.archived++
    })

    // A bracket shows the mirroring. The physical code `[BracketLeft]`
    // matches the key, because Alt+[ types a quote mark on macOS.
    this.hotkeysScope.createHotkey('Alt+[BracketLeft]', () => {
      this.previousPage++
    })

    // A page-level Escape hotkey. While focus is inside an open modal
    // `<dialog>`, the library skips it, so Escape closes the dialog and this
    // callback doesn't run. Escape types no character, so it keeps working
    // while single-key shortcuts are off.
    this.hotkeysScope.createHotkey('Escape', () => {
      this.escapes++
    })
  }

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

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