Skip to content

Lit Example: Hotkey Alternates

import {
  AppHotkeysController,
  FormatForDisplayController,
  HotkeyController,
  defineAppHotkeys,
  detectPlatform,
  provideAppHotkeys,
  resolveHotkeyAlternates,
} 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 { Hotkey } from '@tanstack/lit-hotkeys'

const appHotkeys = defineAppHotkeys({
  'help.open': {
    hotkey: { default: '?', alternates: ['F1'] },
    meta: { name: 'Open help' },
  },
})

declare module '@tanstack/lit-hotkeys' {
  interface Register {
    appHotkeys: typeof appHotkeys
  }
}

provideAppHotkeys(appHotkeys)

@customElement('my-app')
export class MyApp extends LitElement {
  static styles = [
    css`
      :host {
        display: block;
        font-family: system-ui, sans-serif;
      }
    `,
    unsafeCSS(appStyles),
  ]

  // Lit has no provider, so the platform switcher sets the `platform` option
  // of every hotkey and of the formatter. `@hotkey` takes the same hotkey
  // objects, but its options are fixed when the class is defined, so this
  // example uses `HotkeyController` with an options function.
  @state() private platform = detectPlatform()
  @state() private lastFired: string | null = null

  private formatForDisplay = new FormatForDisplayController(this, () => ({
    platform: this.platform,
  }))

  // `context.hotkey` is the hotkey that fired: the first one or an alternate.
  private fire(action: string, hotkey: Hotkey) {
    this.lastFired = `${action} fired from ${this.formatForDisplay.format(hotkey, { sequenceSeparator: ' then ' })}`
  }

  // A platform replaces `default`.
  private deleteItem = new HotkeyController(
    this,
    { default: 'Delete', mac: 'Mod+Backspace' },
    (_event, context) => this.fire('Delete item', context.hotkey),
    () => ({ platform: this.platform }),
  )
  private findNext = new HotkeyController(
    this,
    { default: 'F3', mac: 'Mod+G' },
    (_event, context) => this.fire('Find next', context.hotkey),
    () => ({ platform: this.platform }),
  )

  // `null` leaves a platform without a hotkey.
  private preferences = new HotkeyController(
    this,
    { default: null, mac: 'Mod+,' },
    (_event, context) => this.fire('Preferences', context.hotkey),
    () => ({ platform: this.platform }),
  )
  private properties = new HotkeyController(
    this,
    { default: 'Alt+Enter', mac: null },
    (_event, context) => this.fire('Properties', context.hotkey),
    () => ({ platform: this.platform }),
  )

  // `alternates` adds hotkeys. All of them fire the callback.
  private playOrPause = new HotkeyController(
    this,
    { default: 'Space', alternates: ['K', 'MediaPlayPause'] },
    (_event, context) => this.fire('Play or pause', context.hotkey),
    () => ({ platform: this.platform }),
  )

  // An alternate can be a chord string, a chord object, or a sequence. The
  // hotkeys mix chords and a sequence, so both kinds' options are accepted.
  private openSearch = new HotkeyController(
    this,
    {
      default: 'Mod+K',
      alternates: ['/', { key: 'F', mod: true, shift: true }, ['G', 'S']],
    },
    (_event, context) => this.fire('Open search', context.hotkey),
    () => ({ timeout: 800, requireReset: true, platform: this.platform }),
  )

  // An alternate can differ by platform. Windows and Linux take either
  // hotkey, and macOS takes only Mod+Shift+Z.
  private redo = new HotkeyController(
    this,
    {
      default: 'Mod+Y',
      mac: 'Mod+Shift+Z',
      alternates: [{ default: 'Mod+Shift+Z', mac: null }],
    },
    (_event, context) => this.fire('Redo', context.hotkey),
    () => ({ platform: this.platform }),
  )

  // An array in `alternates` is a sequence, so these two differ.
  private twoAlternates = new HotkeyController(
    this,
    { default: 'X', alternates: ['Q', 'W'] },
    (_event, context) => this.fire('Two alternates', context.hotkey),
    () => ({ platform: this.platform }),
  )
  private oneSequence = new HotkeyController(
    this,
    { default: 'Z', alternates: [['Q', 'E']] },
    (_event, context) => this.fire('One sequence', context.hotkey),
    () => ({ platform: this.platform }),
  )

  // An alternate can name a key by position, such as a numpad key.
  private zoomIn = new HotkeyController(
    this,
    { default: 'Mod+=', alternates: ['Mod+[NumpadAdd]'] },
    (_event, context) => this.fire('Zoom in', context.hotkey),
    () => ({ platform: this.platform }),
  )
  private zoomOut = new HotkeyController(
    this,
    { default: 'Mod+-', alternates: ['Mod+[NumpadSubtract]'] },
    (_event, context) => this.fire('Zoom out', context.hotkey),
    () => ({ platform: this.platform }),
  )

  // App hotkeys take them too. A custom hotkey replaces the whole object.
  private app = new AppHotkeysController(this)
  private openHelp = new HotkeyController(
    this,
    appHotkeys['help.open'],
    (_event, context) => this.fire('Open help', context.hotkey),
    () => ({ platform: this.platform }),
  )

  render() {
    const formatForDisplay = this.formatForDisplay.format
    const helpHotkey = this.app.appHotkeys['help.open']

    return html`
      <div class="app">
        <header>
          <h1>Platform hotkeys and alternates</h1>
          <p>
            Pass an object to <code>HotkeyController</code> or
            <code>@hotkey</code> to give each platform its own hotkey, or to
            give one action more than one hotkey.
          </p>
          <div>
            <button
              aria-pressed=${this.platform === 'mac'}
              @click=${() => (this.platform = 'mac')}
            >
              macOS
            </button>
            <button
              aria-pressed=${this.platform === 'windows'}
              @click=${() => (this.platform = 'windows')}
            >
              Windows
            </button>
            <button
              aria-pressed=${this.platform === 'linux'}
              @click=${() => (this.platform = 'linux')}
            >
              Linux
            </button>
          </div>
          <p>
            These buttons set the <code>platform</code> option of every hotkey
            and of the formatter, which resolves every hotkey object and label.
            <code>Mod</code> then means that platform's key: Command for macOS,
            Control for the others.
          </p>
        </header>

        <main>
          <div class=${this.lastFired ? 'info-box success' : 'info-box'}>
            ${this.lastFired ?? 'Press any hotkey from the tables below.'}
          </div>

          <section class="demo-section">
            <h2>A hotkey per platform</h2>
            <p>
              <code>default</code> is the hotkey. <code>mac</code>,
              <code>windows</code>, and <code>linux</code> replace it on that
              platform, so the default does not fire there.
            </p>
            <table class="shortcut-table">
              <thead>
                <tr>
                  <th>Action</th>
                  <th>Hotkey</th>
                  <th>Written as</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Delete item</td>
                  <td>
                    <kbd
                      >${formatForDisplay({
                        default: 'Delete',
                        mac: 'Mod+Backspace',
                      })}</kbd
                    >
                  </td>
                  <td class="source">
                    ${`{ default: 'Delete', mac: 'Mod+Backspace' }`}
                  </td>
                </tr>
                <tr>
                  <td>Find next</td>
                  <td>
                    <kbd
                      >${formatForDisplay({ default: 'F3', mac: 'Mod+G' })}</kbd
                    >
                  </td>
                  <td class="source">${`{ default: 'F3', mac: 'Mod+G' }`}</td>
                </tr>
              </tbody>
            </table>
          </section>

          <section class="demo-section">
            <h2>A hotkey on some platforms only</h2>
            <p>
              <code>null</code> leaves a platform without a hotkey, and nothing
              registers there. <code>format</code> returns an empty string for
              it. <code>default</code> is required, so a platform is never left
              out by accident.
            </p>
            <table class="shortcut-table">
              <thead>
                <tr>
                  <th>Action</th>
                  <th>Hotkey</th>
                  <th>Written as</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Preferences</td>
                  <td>
                    <kbd
                      >${
                        formatForDisplay({ default: null, mac: 'Mod+,' }) ||
                        'None'
                      }</kbd
                    >
                  </td>
                  <td class="source">${`{ default: null, mac: 'Mod+,' }`}</td>
                </tr>
                <tr>
                  <td>Properties</td>
                  <td>
                    <kbd
                      >${
                        formatForDisplay({ default: 'Alt+Enter', mac: null }) ||
                        'None'
                      }</kbd
                    >
                  </td>
                  <td class="source">
                    ${`{ default: 'Alt+Enter', mac: null }`}
                  </td>
                </tr>
              </tbody>
            </table>
          </section>

          <section class="demo-section">
            <h2>Alternates</h2>
            <p>
              <code>alternates</code> lists more hotkeys for the same action.
              Each one is a chord string, a chord object, or a sequence.
              <code>format</code> shows the first hotkey, or every hotkey when
              you pass <code>alternatesSeparator</code>.
              <code>resolveHotkeyAlternates</code> returns the alternates, to
              format each one yourself.
            </p>
            <table class="shortcut-table">
              <thead>
                <tr>
                  <th>Action</th>
                  <th>Hotkey</th>
                  <th>Alternates</th>
                  <th>Written as</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Play or pause</td>
                  <td>
                    <kbd
                      >${formatForDisplay({
                        default: 'Space',
                        alternates: ['K', 'MediaPlayPause'],
                      })}</kbd
                    >
                  </td>
                  <td>
                    ${resolveHotkeyAlternates(
                      { default: 'Space', alternates: ['K', 'MediaPlayPause'] },
                      this.platform,
                    ).map(
                      (alternate) =>
                        html`<kbd>${formatForDisplay(alternate)}</kbd>`,
                    )}
                  </td>
                  <td class="source">
                    ${`{ default: 'Space', alternates: ['K', 'MediaPlayPause'] }`}
                  </td>
                </tr>
                <tr>
                  <td>Open search</td>
                  <td>
                    <kbd
                      >${formatForDisplay({
                        default: 'Mod+K',
                        alternates: [
                          '/',
                          { key: 'F', mod: true, shift: true },
                          ['G', 'S'],
                        ],
                      })}</kbd
                    >
                  </td>
                  <td>
                    ${resolveHotkeyAlternates(
                      {
                        default: 'Mod+K',
                        alternates: [
                          '/',
                          { key: 'F', mod: true, shift: true },
                          ['G', 'S'],
                        ],
                      },
                      this.platform,
                    ).map(
                      (alternate) =>
                        html`<kbd
                          >${formatForDisplay(alternate, {
                            sequenceSeparator: ' then ',
                          })}</kbd
                        >`,
                    )}
                  </td>
                  <td class="source">
                    ${`{
  default: 'Mod+K',
  alternates: [
    '/',
    { key: 'F', mod: true, shift: true },
    ['G', 'S'],
  ],
}`}
                  </td>
                </tr>
              </tbody>
            </table>
          </section>

          <section class="demo-section">
            <h2>Alternates per platform</h2>
            <p>
              An alternate can be an object with a <code>default</code> and
              platforms. It resolves the same way as the first hotkey. Switch
              the platform above to see the alternate come and go.
            </p>
            <table class="shortcut-table">
              <thead>
                <tr>
                  <th>Action</th>
                  <th>Hotkey</th>
                  <th>Alternates</th>
                  <th>Written as</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Redo</td>
                  <td>
                    <kbd
                      >${formatForDisplay({
                        default: 'Mod+Y',
                        mac: 'Mod+Shift+Z',
                      })}</kbd
                    >
                  </td>
                  <td>
                    ${resolveHotkeyAlternates(
                      {
                        default: 'Mod+Y',
                        mac: 'Mod+Shift+Z',
                        alternates: [{ default: 'Mod+Shift+Z', mac: null }],
                      },
                      this.platform,
                    ).map(
                      (alternate) =>
                        html`<kbd>${formatForDisplay(alternate)}</kbd>`,
                    )}
                  </td>
                  <td class="source">
                    ${`{
  default: 'Mod+Y',
  mac: 'Mod+Shift+Z',
  alternates: [{ default: 'Mod+Shift+Z', mac: null }],
}`}
                  </td>
                </tr>
              </tbody>
            </table>
          </section>

          <section class="demo-section">
            <h2>Two alternates or one sequence</h2>
            <p>
              An array in <code>alternates</code> is a sequence. The first row
              fires from <kbd>X</kbd>, <kbd>Q</kbd>, or <kbd>W</kbd>. The second
              fires from <kbd>Z</kbd>, or from <kbd>Q</kbd> then <kbd>E</kbd>.
            </p>
            <table class="shortcut-table">
              <thead>
                <tr>
                  <th>Action</th>
                  <th>Written as</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Two alternates</td>
                  <td class="source">
                    ${`{ default: 'X', alternates: ['Q', 'W'] }`}
                  </td>
                </tr>
                <tr>
                  <td>One sequence</td>
                  <td class="source">
                    ${`{ default: 'Z', alternates: [['Q', 'E']] }`}
                  </td>
                </tr>
              </tbody>
            </table>
          </section>

          <section class="demo-section">
            <h2>Every hotkey in one label</h2>
            <p>
              The alternates here name the numpad keys by position, and the
              labels use <code>alternatesSeparator</code> to list every hotkey.
            </p>
            <table class="shortcut-table">
              <thead>
                <tr>
                  <th>Action</th>
                  <th>Hotkey</th>
                  <th>Written as</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Zoom in</td>
                  <td>
                    <kbd
                      >${formatForDisplay(
                        { default: 'Mod+=', alternates: ['Mod+[NumpadAdd]'] },
                        { alternatesSeparator: ' or ' },
                      )}</kbd
                    >
                  </td>
                  <td class="source">
                    ${`{ default: 'Mod+=', alternates: ['Mod+[NumpadAdd]'] }`}
                  </td>
                </tr>
                <tr>
                  <td>Zoom out</td>
                  <td>
                    <kbd
                      >${formatForDisplay(
                        {
                          default: 'Mod+-',
                          alternates: ['Mod+[NumpadSubtract]'],
                        },
                        { alternatesSeparator: ' or ' },
                      )}</kbd
                    >
                  </td>
                  <td class="source">
                    ${`{ default: 'Mod+-', alternates: ['Mod+[NumpadSubtract]'] }`}
                  </td>
                </tr>
              </tbody>
            </table>
          </section>

          <section class="demo-section">
            <h2>With app hotkeys</h2>
            <p>
              <code>defineAppHotkeys</code> accepts the same objects. A custom
              hotkey replaces the first hotkey and the alternates, so after you
              set one, <kbd>?</kbd> and <kbd>F1</kbd> stop working.
            </p>
            <table class="shortcut-table">
              <thead>
                <tr>
                  <th>Action</th>
                  <th>Hotkey</th>
                  <th>Alternates</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Open help</td>
                  <td>
                    <kbd
                      >${
                        (helpHotkey.hotkey &&
                          formatForDisplay(helpHotkey.hotkey)) ||
                        'Unassigned'
                      }</kbd
                    >
                  </td>
                  <td>
                    ${resolveHotkeyAlternates(
                      helpHotkey.hotkey,
                      this.platform,
                    ).map(
                      (alternate) =>
                        html`<kbd>${formatForDisplay(alternate)}</kbd>`,
                    )}
                  </td>
                </tr>
              </tbody>
            </table>
            <p>
              <button
                @click=${() => this.app.setCustomHotkey('help.open', 'H')}
              >
                Set the custom hotkey to H
              </button>
              <button @click=${() => this.app.resetCustomHotkey('help.open')}>
                Restore the default
              </button>
            </p>
          </section>

          <section class="demo-section">
            <h2>Usage</h2>
            <pre class="code-block">
${`import { hotkey } from '@tanstack/lit-hotkeys'

class Editor extends LitElement {
  // A platform replaces the default
  @hotkey({ default: 'Mod+Y', mac: 'Mod+Shift+Z' })
  redo() {}

  // macOS only
  @hotkey({ default: null, mac: 'Mod+,' })
  openPreferences() {}

  // Alternates fire the same method
  @hotkey({ default: 'Space', alternates: ['K', 'MediaPlayPause'] })
  togglePlay() {}

  // An alternate can be a sequence
  @hotkey({ default: 'Mod+K', alternates: ['/', ['G', 'S']] })
  openSearch() {}

  // An alternate can differ by platform
  @hotkey({
    default: 'Mod+Y',
    mac: 'Mod+Shift+Z',
    alternates: [{ default: 'Mod+Shift+Z', mac: null }],
  })
  redoEither() {}
}`}</pre>
          </section>
        </main>
      </div>
    `
  }
}

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