Skip to content

Ember Example: UseHotkey Alternates

import { array, fn, hash } from '@ember/helper'
import { on } from '@ember/modifier'
import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import {
  createHotkeysScope,
  defineAppHotkeys,
  defineHotkey,
  detectPlatform,
  provideAppHotkeys,
  resolveHotkeyAlternates,
  useAppHotkeys,
  useCustomHotkeys,
  useFormatForDisplay,
} from '@tanstack/ember-hotkeys'
import type {
  HotkeyCallback,
  HotkeyPlatform,
} from '@tanstack/ember-hotkeys'

const eq = (a: unknown, b: unknown) => a === b
const or = <T, U>(a: T, b: U) => a || b

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

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

// Ember has no provider component. This publishes the app hotkeys before the
// application boots.
const { store } = provideAppHotkeys(appHotkeys)

const searchSource = `(hash
  default='Mod+K'
  alternates=(array
    '/'
    (hash key='F' mod=true shift=true)
    (array 'G' 'S')
  )
)`

const redoSource = `(hash
  default='Mod+Y'
  mac='Mod+Shift+Z'
  alternates=(array (hash default='Mod+Shift+Z' mac=null))
)`

const usage = `import { array, hash } from '@ember/helper'
import { useHotkey } from '@tanstack/ember-hotkeys'

<template>
  {{! A platform replaces the default }}
  {{useHotkey (hash default='Mod+Y' mac='Mod+Shift+Z') this.redo}}

  {{! macOS only }}
  {{useHotkey (hash default=null mac='Mod+,') this.openPreferences}}

  {{! Alternates fire the same callback }}
  {{useHotkey
    (hash default='Space' alternates=(array 'K' 'MediaPlayPause'))
    this.togglePlay
  }}

  {{! An alternate can be a sequence }}
  {{useHotkey
    (hash default='Mod+K' alternates=(array '/' (array 'G' 'S')))
    this.openSearch
  }}

  {{! An alternate can differ by platform }}
  {{useHotkey
    (hash
      default='Mod+Y'
      mac='Mod+Shift+Z'
      alternates=(array (hash default='Mod+Shift+Z' mac=null))
    )
    this.redo
  }}
</template>`

class App extends Component {
  @tracked platform = detectPlatform()
  @tracked lastFired: string | null = null

  // The scope's helpers register for this platform, and register again when it
  // changes.
  hotkeys = createHotkeysScope(() => ({ platform: this.platform }))
  // Formats for the scope's platform.
  formatForDisplay = useFormatForDisplay(this.hotkeys)

  setPlatform = (platform: HotkeyPlatform) => {
    this.platform = platform
    // App hotkeys compare hotkeys, such as for conflicts, on this platform.
    store.setOptions({ platform })
  }

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

  // `resolveHotkeyAlternates` returns the hotkeys after the first one.
  get playAlternates() {
    return resolveHotkeyAlternates(
      { default: 'Space', alternates: ['K', 'MediaPlayPause'] },
      this.platform,
    )
  }
  get searchAlternates() {
    return resolveHotkeyAlternates(
      {
        default: 'Mod+K',
        alternates: ['/', { key: 'F', mod: true, shift: true }, ['G', 'S']],
      },
      this.platform,
    )
  }
  get redoAlternates() {
    return resolveHotkeyAlternates(
      {
        default: 'Mod+Y',
        mac: 'Mod+Shift+Z',
        alternates: [{ default: 'Mod+Shift+Z', mac: null }],
      },
      this.platform,
    )
  }

  // `useHotkeys` takes the same objects.
  get zoomHotkeys() {
    return [
      defineHotkey({
        hotkey: { default: 'Mod+=', alternates: ['Mod+[NumpadAdd]'] },
        callback: this.fire('Zoom in'),
      }),
      defineHotkey({
        hotkey: { default: 'Mod+-', alternates: ['Mod+[NumpadSubtract]'] },
        callback: this.fire('Zoom out'),
      }),
    ]
  }

  // App hotkeys take them too. A custom hotkey replaces the whole object.
  appHotkeys = useAppHotkeys(this)
  customHotkeys = useCustomHotkeys(this)
  get helpHotkey() {
    return this.appHotkeys.value['help.open']
  }
  get helpLabel() {
    const { hotkey } = this.helpHotkey
    return (hotkey && this.formatForDisplay(hotkey)) || 'Unassigned'
  }
  setHelpToH = () => this.customHotkeys.setCustomHotkey('help.open', 'H')
  restoreHelp = () => this.customHotkeys.resetCustomHotkey('help.open')

  <template>
    {{! A platform replaces `default`. }}
    {{this.hotkeys.useHotkey
      (hash default='Delete' mac='Mod+Backspace')
      (this.fire 'Delete item')
    }}
    {{this.hotkeys.useHotkey
      (hash default='F3' mac='Mod+G')
      (this.fire 'Find next')
    }}

    {{! `null` leaves a platform without a hotkey. }}
    {{this.hotkeys.useHotkey
      (hash default=null mac='Mod+,')
      (this.fire 'Preferences')
    }}
    {{this.hotkeys.useHotkey
      (hash default='Alt+Enter' mac=null)
      (this.fire 'Properties')
    }}

    {{! `alternates` adds hotkeys. All of them fire the callback. }}
    {{this.hotkeys.useHotkey
      (hash default='Space' alternates=(array 'K' 'MediaPlayPause'))
      (this.fire 'Play or pause')
    }}

    {{! 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. }}
    {{this.hotkeys.useHotkey
      (hash
        default='Mod+K'
        alternates=(array
          '/' (hash key='F' mod=true shift=true) (array 'G' 'S')
        )
      )
      (this.fire 'Open search')
      timeout=800
      requireReset=true
    }}

    {{! An alternate can differ by platform. Windows and Linux take either
      hotkey, and macOS takes only Mod+Shift+Z. }}
    {{this.hotkeys.useHotkey
      (hash
        default='Mod+Y'
        mac='Mod+Shift+Z'
        alternates=(array (hash default='Mod+Shift+Z' mac=null))
      )
      (this.fire 'Redo')
    }}

    {{! An array in `alternates` is a sequence, so these two differ. }}
    {{this.hotkeys.useHotkey
      (hash default='X' alternates=(array 'Q' 'W'))
      (this.fire 'Two alternates')
    }}
    {{this.hotkeys.useHotkey
      (hash default='Z' alternates=(array (array 'Q' 'E')))
      (this.fire 'One sequence')
    }}

    {{this.hotkeys.useHotkeys this.zoomHotkeys}}

    {{this.hotkeys.useHotkey this.helpHotkey (this.fire 'Open help')}}

    <div class='app'>
      <header>
        <h1>Platform hotkeys and alternates</h1>
        <p>
          Pass an object to
          <code>useHotkey</code>
          to give each platform its own hotkey, or to give one action more than
          one hotkey.
        </p>
        <div>
          <button
            type='button'
            aria-pressed={{if (eq this.platform 'mac') 'true' 'false'}}
            {{on 'click' (fn this.setPlatform 'mac')}}
          >
            macOS
          </button>
          <button
            type='button'
            aria-pressed={{if (eq this.platform 'windows') 'true' 'false'}}
            {{on 'click' (fn this.setPlatform 'windows')}}
          >
            Windows
          </button>
          <button
            type='button'
            aria-pressed={{if (eq this.platform 'linux') 'true' 'false'}}
            {{on 'click' (fn this.setPlatform 'linux')}}
          >
            Linux
          </button>
        </div>
        <p>
          These buttons set the platform of a
          <code>createHotkeysScope</code>
          scope, 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={{if this.lastFired 'info-box success' 'info-box'}}>
          {{or 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>{{this.formatForDisplay
                      (hash default='Delete' mac='Mod+Backspace')
                    }}</kbd>
                </td>
                <td class='source'>(hash default='Delete' mac='Mod+Backspace')</td>
              </tr>
              <tr>
                <td>Find next</td>
                <td>
                  <kbd>{{this.formatForDisplay
                      (hash default='F3' mac='Mod+G')
                    }}</kbd>
                </td>
                <td class='source'>(hash 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>formatForDisplay</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>{{or
                      (this.formatForDisplay (hash default=null mac='Mod+,'))
                      'None'
                    }}</kbd>
                </td>
                <td class='source'>(hash default=null mac='Mod+,')</td>
              </tr>
              <tr>
                <td>Properties</td>
                <td>
                  <kbd>{{or
                      (this.formatForDisplay
                        (hash default='Alt+Enter' mac=null)
                      )
                      'None'
                    }}</kbd>
                </td>
                <td class='source'>(hash 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>formatForDisplay</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>{{this.formatForDisplay
                      (hash
                        default='Space' alternates=(array 'K' 'MediaPlayPause')
                      )
                    }}</kbd>
                </td>
                <td>
                  {{#each this.playAlternates as |alternate|}}
                    <kbd>{{this.formatForDisplay alternate}}</kbd>
                  {{/each}}
                </td>
                <td class='source'>(hash default='Space' alternates=(array 'K' 'MediaPlayPause'))</td>
              </tr>
              <tr>
                <td>Open search</td>
                <td>
                  <kbd>{{this.formatForDisplay
                      (hash
                        default='Mod+K'
                        alternates=(array
                          '/' (hash key='F' mod=true shift=true) (array 'G' 'S')
                        )
                      )
                    }}</kbd>
                </td>
                <td>
                  {{#each this.searchAlternates as |alternate|}}
                    <kbd>{{this.formatForDisplay
                        alternate
                        (hash sequenceSeparator=' then ')
                      }}</kbd>
                  {{/each}}
                </td>
                <td class='source'>{{searchSource}}</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>{{this.formatForDisplay
                      (hash default='Mod+Y' mac='Mod+Shift+Z')
                    }}</kbd>
                </td>
                <td>
                  {{#each this.redoAlternates as |alternate|}}
                    <kbd>{{this.formatForDisplay alternate}}</kbd>
                  {{/each}}
                </td>
                <td class='source'>{{redoSource}}</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'>(hash default='X' alternates=(array 'Q' 'W'))</td>
              </tr>
              <tr>
                <td>One sequence</td>
                <td class='source'>(hash default='Z' alternates=(array (array 'Q' 'E')))</td>
              </tr>
            </tbody>
          </table>
        </section>

        <section class='demo-section'>
          <h2>With useHotkeys</h2>
          <p>
            Each item's
            <code>hotkey</code>
            accepts the same objects. 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>{{this.formatForDisplay
                      (hash
                        default='Mod+=' alternates=(array 'Mod+[NumpadAdd]')
                      )
                      (hash alternatesSeparator=' or ')
                    }}</kbd>
                </td>
                <td class='source'>{ default: 'Mod+=', alternates: ['Mod+[NumpadAdd]'] }</td>
              </tr>
              <tr>
                <td>Zoom out</td>
                <td>
                  <kbd>{{this.formatForDisplay
                      (hash
                        default='Mod+-'
                        alternates=(array 'Mod+[NumpadSubtract]')
                      )
                      (hash 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>{{this.helpLabel}}</kbd>
                </td>
                <td>
                  {{#each
                    (resolveHotkeyAlternates
                      this.helpHotkey.hotkey this.platform
                    )
                    as |alternate|
                  }}
                    <kbd>{{this.formatForDisplay alternate}}</kbd>
                  {{/each}}
                </td>
              </tr>
            </tbody>
          </table>
          <p>
            <button type='button' {{on 'click' this.setHelpToH}}>
              Set the custom hotkey to H
            </button>
            <button type='button' {{on 'click' this.restoreHelp}}>
              Restore the default
            </button>
          </p>
        </section>

        <section class='demo-section'>
          <h2>Usage</h2>
          <pre class='code-block'>{{usage}}</pre>
        </section>
      </main>
    </div>
  </template>
}
export default App