Skip to content

Alpine Example: Keyboard Layouts

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

// Hotkey strings accept the keys that US and German keyboards type. Without
// this, only US keys type-check, and `Mod+Ö` is an error. This changes types
// only: matching works the same with or without it. Hotkeys written in HTML
// attributes aren't type-checked, so this applies to TypeScript code only.
declare module '@tanstack/alpine-hotkeys' {
  interface Register {
    keys: UsKeys | GermanKeys
  }
}

// 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()

  // Labels physical keys such as `[KeyW]` with the character the user's
  // keyboard layout types there, once the browser reports the layout.
  formatForDisplay = this.hotkeysScope.createFormatForDisplay()
  // The browser's layout in `.value`, as a map from physical code to
  // character, such as KeyQ to 'a' on French AZERTY. `null` until it loads,
  // and always `null` in Firefox and Safari, which don't report a layout.
  keyboardLayout = this.hotkeysScope.createKeyboardLayout()

  germanFired = 'none'
  everyLayoutFired = 'none'
  physicalFired = 'none'

  init() {
    // These type-check because German keys are registered above.
    this.hotkeysScope.createHotkey('Mod+Ö', () => {
      this.germanFired = 'Toggle comment'
    })
    this.hotkeysScope.createHotkey('Mod+Shift+Ä', () => {
      this.germanFired = 'Add annotation'
    })
    this.hotkeysScope.createHotkey('ß', () => {
      this.germanFired = 'Toggle sidebar'
    })
    this.hotkeysScope.createHotkey('§', () => {
      this.germanFired = 'Show sections'
    })

    // A to Z, 0 to 9, named keys, and physical codes type-check under every
    // registration. Letters match by the character typed, so Mod+K fires on
    // the key labeled K on any Latin layout.
    this.hotkeysScope.createHotkey('Mod+K', () => {
      this.everyLayoutFired = 'Open command palette'
    })
    this.hotkeysScope.createHotkey('Mod+Enter', () => {
      this.everyLayoutFired = 'Send'
    })
    this.hotkeysScope.createHotkey('Escape', () => {
      this.everyLayoutFired = 'Dismiss'
    })

    // A physical code in brackets matches a key position, not a character.
    // `[KeyW]` is the key at the US W position, which types Z on French
    // AZERTY, so WASD movement stays in the same place on every keyboard.
    this.hotkeysScope.createHotkey('[KeyW]', () => {
      this.physicalFired = 'Move up'
    })
    this.hotkeysScope.createHotkey('[KeyA]', () => {
      this.physicalFired = 'Move left'
    })
    this.hotkeysScope.createHotkey('[KeyS]', () => {
      this.physicalFired = 'Move down'
    })
    this.hotkeysScope.createHotkey('[KeyD]', () => {
      this.physicalFired = 'Move right'
    })
    // Mod+Z would undo in a focused text field. The US Z position types Y on
    // German QWERTZ, so the label reads Ctrl+Y there.
    this.hotkeysScope.createHotkey('Mod+[KeyZ]', () => {
      this.physicalFired = 'Undo'
    })
  }

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

class OwnLayout {
  // `keyboardLayout: false` stops labels from this owner from asking the
  // browser for the layout. Without it, a label with no `layoutMap` shows
  // the browser's layout, as in the sections above.
  private hotkeysScope = createHotkeysScope({ keyboardLayout: false })

  formatForDisplay = this.hotkeysScope.createFormatForDisplay()
  layout = 'us'

  // Any `{ get(code) }` object works as a layout map. Codes it leaves out
  // keep their US label.
  get layoutMap() {
    return this.layout === 'fr'
      ? new Map([
          ['KeyQ', 'a'],
          ['KeyA', 'q'],
          ['KeyW', 'z'],
          ['KeyZ', 'w'],
        ])
      : this.layout === 'de'
        ? new Map([
            ['KeyY', 'z'],
            ['KeyZ', 'y'],
          ])
        : undefined
  }

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

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