Skip to content

Lit Example: Keyboard Layouts

import {
  FormatForDisplayController,
  KeyboardLayoutController,
  hotkey,
} from '@tanstack/lit-hotkeys'
import { LitElement, css, html, unsafeCSS } from 'lit'
import { customElement, state } from 'lit/decorators.js'
import appStyles from './index.css?raw'
import type { GermanKeys, UsKeys } from '@tanstack/lit-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/lit-hotkeys' {
  interface Register {
    keys: UsKeys | GermanKeys
  }
}

@customElement('my-app')
export class MyApp extends LitElement {
  static styles = [
    css`
      :host {
        display: block;
        margin: 0;
        font-family: system-ui, -apple-system, sans-serif;
        background: #f5f5f5;
        color: #333;
        box-sizing: border-box;
      }
      :host *,
      :host *::before,
      :host *::after {
        box-sizing: border-box;
      }
    `,
    unsafeCSS(appStyles),
  ]

  @state() private germanFired = 'none'
  @state() private everyLayoutFired = 'none'
  @state() private physicalFired = 'none'
  @state() private layout = 'us'

  // Labels physical keys such as `[KeyW]` with the character the user's
  // keyboard layout types there, once the browser reports the layout.
  private formatForDisplay = new FormatForDisplayController(this)
  // `keyboardLayout: false` stops this formatter from asking the browser for
  // the layout. Lit has no provider, so the last section uses this second
  // controller. Without it, a label with no `layoutMap` shows the browser's
  // layout, as in the sections above.
  private formatWithOwnLayout = new FormatForDisplayController(this, {
    keyboardLayout: false,
  })
  // 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.
  private keyboardLayout = new KeyboardLayoutController(this)

  // These type-check because German keys are registered above.
  @hotkey('Mod+Ö')
  toggleComment() {
    this.germanFired = 'Toggle comment'
  }

  @hotkey('Mod+Shift+Ä')
  addAnnotation() {
    this.germanFired = 'Add annotation'
  }

  @hotkey('ß')
  toggleSidebar() {
    this.germanFired = 'Toggle sidebar'
  }

  @hotkey('§')
  showSections() {
    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.
  @hotkey('Mod+K')
  openCommandPalette() {
    this.everyLayoutFired = 'Open command palette'
  }

  @hotkey('Mod+Enter')
  send() {
    this.everyLayoutFired = 'Send'
  }

  @hotkey('Escape')
  dismiss() {
    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.
  @hotkey('[KeyW]')
  moveUp() {
    this.physicalFired = 'Move up'
  }

  @hotkey('[KeyA]')
  moveLeft() {
    this.physicalFired = 'Move left'
  }

  @hotkey('[KeyS]')
  moveDown() {
    this.physicalFired = 'Move down'
  }

  @hotkey('[KeyD]')
  moveRight() {
    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.
  @hotkey('Mod+[KeyZ]')
  undo() {
    this.physicalFired = 'Undo'
  }

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

    return html`
      <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>${formatForDisplay('Mod+Ö')}</kbd> Toggle comment
              </div>
              <div class="hotkey-row">
                <kbd>${formatForDisplay('Mod+Shift+Ä')}</kbd> Add annotation
              </div>
              <div class="hotkey-row">
                <kbd>${formatForDisplay('ß')}</kbd> Toggle sidebar
              </div>
              <div class="hotkey-row">
                <kbd>${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>${formatForDisplay('Mod+K')}</kbd> Open command palette
              </div>
              <div class="hotkey-row">
                <kbd>${formatForDisplay('Mod+Enter')}</kbd> Send
              </div>
              <div class="hotkey-row">
                <kbd>${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>${formatForDisplay('[KeyW]')}</kbd> Move up
              </div>
              <div class="hotkey-row">
                <kbd>${formatForDisplay('[KeyA]')}</kbd> Move left
              </div>
              <div class="hotkey-row">
                <kbd>${formatForDisplay('[KeyS]')}</kbd> Move down
              </div>
              <div class="hotkey-row">
                <kbd>${formatForDisplay('[KeyD]')}</kbd> Move right
              </div>
              <div class="hotkey-row">
                <kbd>${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">
              ${
                layoutMap
                  ? '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:
              ${[
                'KeyQ',
                'KeyW',
                'KeyE',
                'KeyR',
                'KeyT',
                'KeyY',
                'KeyU',
                'KeyI',
                'KeyO',
                'KeyP',
              ].map(
                // Falls back to the US letter, the code without `Key`.
                (code) =>
                  html`<kbd
                    >${(layoutMap?.get(code) ?? code.slice(3)).toUpperCase()}</kbd
                  > `,
              )}
            </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
                .value=${this.layout}
                @change=${(e: Event) =>
                  (this.layout = (e.target as HTMLSelectElement).value)}
              >
                <option value="us">US QWERTY</option>
                <option value="fr">French AZERTY</option>
                <option value="de">German QWERTZ</option>
              </select>
            </label>
            <p role="status">
              Move:
              ${formatWithOwnLayout('[KeyW]', { layoutMap: ownLayoutMap })}
              ${formatWithOwnLayout('[KeyA]', { layoutMap: ownLayoutMap })}
              ${formatWithOwnLayout('[KeyS]', { layoutMap: ownLayoutMap })}
              ${formatWithOwnLayout('[KeyD]', { layoutMap: ownLayoutMap })}.
              Undo:
              ${formatWithOwnLayout('Mod+[KeyZ]', { layoutMap: ownLayoutMap })}
            </p>
          </section>
        </main>
      </div>
    `
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'my-app': MyApp
  }
}