Skip to content

Ember Example: Keyboard Layouts

import { array, hash } from '@ember/helper'
import { on } from '@ember/modifier'
import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import {
  createHotkeysScope,
  useFormatForDisplay,
  useHotkey,
  useKeyboardLayout,
} from '@tanstack/ember-hotkeys'
import type { GermanKeys, UsKeys } from '@tanstack/ember-hotkeys'

// 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.
declare module '@tanstack/ember-hotkeys' {
  interface Register {
    keys: UsKeys | GermanKeys
  }
}

class App extends Component {
  // Labels physical keys such as `[KeyW]` with the character the user's
  // keyboard layout types there, once the browser reports the layout.
  formatForDisplay = useFormatForDisplay()
  // The browser's layout 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.
  layout = useKeyboardLayout(this)
  // `keyboardLayout: false` stops labels from this formatter asking the
  // browser for the layout. Without it, a label with no `layoutMap` shows the
  // browser's layout, as above.
  ownLayoutHotkeys = createHotkeysScope({ keyboardLayout: false })
  formatForOwnLayout = useFormatForDisplay(this.ownLayoutHotkeys)

  @tracked germanFired = 'none'
  @tracked everyLayoutFired = 'none'
  @tracked physicalFired = 'none'
  @tracked ownLayout = 'us'

  toggleComment = () => (this.germanFired = 'Toggle comment')
  addAnnotation = () => (this.germanFired = 'Add annotation')
  toggleSidebar = () => (this.germanFired = 'Toggle sidebar')
  showSections = () => (this.germanFired = 'Show sections')
  openCommandPalette = () => (this.everyLayoutFired = 'Open command palette')
  send = () => (this.everyLayoutFired = 'Send')
  dismiss = () => (this.everyLayoutFired = 'Dismiss')
  moveUp = () => (this.physicalFired = 'Move up')
  moveLeft = () => (this.physicalFired = 'Move left')
  moveDown = () => (this.physicalFired = 'Move down')
  moveRight = () => (this.physicalFired = 'Move right')
  undo = () => (this.physicalFired = 'Undo')

  // Falls back to the US letter, the code without `Key`.
  keyLabel = (code: string) =>
    (this.layout.value?.get(code) ?? code.slice(3)).toUpperCase()

  setOwnLayout = (event: Event) =>
    (this.ownLayout = (event.target as HTMLSelectElement).value)

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

  <template>
    {{! These type-check because German keys are registered above. }}
    {{useHotkey 'Mod+Ö' this.toggleComment}}
    {{useHotkey 'Mod+Shift+Ä' this.addAnnotation}}
    {{useHotkey 'ß' this.toggleSidebar}}
    {{useHotkey '§' this.showSections}}

    {{! 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. }}
    {{useHotkey 'Mod+K' this.openCommandPalette}}
    {{useHotkey 'Mod+Enter' this.send}}
    {{useHotkey 'Escape' this.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. }}
    {{useHotkey '[KeyW]' this.moveUp}}
    {{useHotkey '[KeyA]' this.moveLeft}}
    {{useHotkey '[KeyS]' this.moveDown}}
    {{useHotkey '[KeyD]' this.moveRight}}
    {{! 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. }}
    {{useHotkey 'Mod+[KeyZ]' this.undo}}

    <div class='app'>
      <header>
        <h1>Keyboard Layouts</h1>
        <p>
          Type hotkeys with keys from other layouts, match keys by position, and
          label them with the characters on the user's keyboard.
        </p>
      </header>

      <main>
        <section class='demo-section'>
          <h2>German keys</h2>
          <p class='note'>
            Switch your keyboard layout to German to press these.
          </p>
          <div class='hotkey-list'>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay 'Mod+Ö'}}</kbd>
              Toggle comment
            </div>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay 'Mod+Shift+Ä'}}</kbd>
              Add annotation
            </div>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay 'ß'}}</kbd>
              Toggle sidebar
            </div>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay '§'}}</kbd>
              Show sections
            </div>
          </div>
          <p role='status'>Last fired: {{this.germanFired}}</p>
        </section>

        <section class='demo-section'>
          <h2>Keys on every layout</h2>
          <div class='hotkey-list'>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay 'Mod+K'}}</kbd>
              Open command palette
            </div>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay 'Mod+Enter'}}</kbd>
              Send
            </div>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay 'Escape'}}</kbd>
              Dismiss
            </div>
          </div>
          <p role='status'>Last fired: {{this.everyLayoutFired}}</p>
        </section>

        <section class='demo-section'>
          <h2>Physical keys</h2>
          <p class='note'>
            These labels show the characters on your keyboard. On French AZERTY,
            the movement keys read Z Q S D.
          </p>
          <div class='hotkey-list'>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay '[KeyW]'}}</kbd>
              Move up
            </div>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay '[KeyA]'}}</kbd>
              Move left
            </div>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay '[KeyS]'}}</kbd>
              Move down
            </div>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay '[KeyD]'}}</kbd>
              Move right
            </div>
            <div class='hotkey-row'>
              <kbd>{{this.formatForDisplay 'Mod+[KeyZ]'}}</kbd>
              Undo
            </div>
          </div>
          <p role='status'>Last fired: {{this.physicalFired}}</p>
        </section>

        <section class='demo-section'>
          <h2>On-screen keyboard</h2>
          <p class='note'>
            {{if
              this.layout.value
              'The top letter row of your keyboard layout.'
              'No layout from the browser, so this is the US top row.'
            }}
          </p>
          <p role='status'>
            Top row:
            {{#each
              (array
                'KeyQ' 'KeyW' 'KeyE' 'KeyR' 'KeyT' 'KeyY' 'KeyU' 'KeyI' 'KeyO'
                'KeyP'
              )
              as |code|
            }}
              <kbd>{{this.keyLabel code}}</kbd>
            {{/each}}
          </p>
        </section>

        <section class='demo-section'>
          <h2>Supply your own layout</h2>
          <p class='note'>
            When your app stores the user's layout, pass it as
            <code>layoutMap</code>. These are the physical keys from above. This
            section's formatter sets
            <code>keyboardLayout: false</code>, so US QWERTY shows US keys
            whatever your keyboard is.
          </p>
          <label>
            Keyboard layout
            <select {{on 'change' this.setOwnLayout}}>
              <option value='us'>US QWERTY</option>
              <option value='fr'>French AZERTY</option>
              <option value='de'>German QWERTZ</option>
            </select>
          </label>
          <p role='status'>
            Move:
            {{this.formatForOwnLayout '[KeyW]' (hash layoutMap=this.layoutMap)}}
            {{this.formatForOwnLayout '[KeyA]' (hash layoutMap=this.layoutMap)}}
            {{this.formatForOwnLayout '[KeyS]' (hash layoutMap=this.layoutMap)}}
            {{this.formatForOwnLayout
              '[KeyD]'
              (hash layoutMap=this.layoutMap)
            }}. Undo:
            {{this.formatForOwnLayout
              'Mod+[KeyZ]'
              (hash layoutMap=this.layoutMap)
            }}
          </p>
        </section>
      </main>
    </div>
  </template>
}
export default App