Skip to content

Ember Example: UseHotkeys Sequences

import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import { array } from '@ember/helper'
import { on } from '@ember/modifier'
import {
  defineHotkey,
  useFormatForDisplay,
  useHotkeyRegistrations,
  useHotkeys,
} from '@tanstack/ember-hotkeys'
import type {
  EmberHotkeyDefinition,
  HotkeyRegistrationView,
} from '@tanstack/ember-hotkeys'

// Sequence views carry matchedStepCount, the steps pressed so far in the
// current attempt. Chord views don't.
const progress = (reg: HotkeyRegistrationView) =>
  reg.kind === 'sequence'
    ? `${reg.matchedStepCount} of ${reg.hotkey.length}`
    : 'chord'

export default class App extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked lastCommand = 'none'
  @tracked vimEnabled = true
  @tracked konamiCount = 0
  @tracked konamiSteps = 0
  @tracked sideCount = 0

  toggleVim = (event: Event) =>
    (this.vimEnabled = (event.target as HTMLInputElement).checked)

  // Arrays are sequences, and chords can share the list. A sequence of
  // letters counts as a character-key shortcut, so the checkbox gives users
  // a way to turn the list off.
  vimCommands: Array<EmberHotkeyDefinition> = [
    {
      hotkey: ['G', 'G'],
      callback: () => (this.lastCommand = 'Go to top'),
      options: { meta: { name: 'Go to top' } },
    },
    {
      hotkey: 'Shift+G',
      callback: () => (this.lastCommand = 'Go to bottom'),
      options: { meta: { name: 'Go to bottom' } },
    },
    {
      hotkey: ['D', 'D'],
      callback: () => (this.lastCommand = 'Delete line'),
      options: { meta: { name: 'Delete line' } },
    },
    {
      hotkey: ['D', 'W'],
      callback: () => (this.lastCommand = 'Delete word'),
      options: { meta: { name: 'Delete word' } },
    },
    {
      hotkey: ['C', 'I', 'W'],
      callback: () => (this.lastCommand = 'Change inner word'),
      options: { meta: { name: 'Change inner word' } },
    },
  ]

  // useHotkeys gives every array item one type that fits any hotkey, so an
  // item's callback `context` can be a chord or a sequence. defineHotkey
  // types one definition by its hotkey and returns it unchanged. This hotkey
  // is a sequence, so `context.parsedSequence` needs no kind check, and
  // `requireReset` would be a type error because it applies only to chords.
  konami = defineHotkey({
    hotkey: ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown'],
    callback: (_event, context) => {
      this.konamiCount++
      this.konamiSteps = context.parsedSequence.length
    },
    // Allow 2 seconds between steps instead of the default 1 second.
    options: { timeout: 2000, meta: { name: 'Konami code' } },
  })

  // A defined hotkey and an inline item can share one array.
  arrowSequences: Array<EmberHotkeyDefinition> = [
    this.konami,
    {
      hotkey: ['ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight'],
      callback: () => this.sideCount++,
      options: { meta: { name: 'Side to side' } },
    },
  ]

  // Every registration on the page, chords and sequences.
  registrations = useHotkeyRegistrations(this)

  <template>
    {{! Named arguments hold options for every item. timeout reaches only
        the sequences, so the Shift+G chord ignores it. }}
    {{useHotkeys this.vimCommands timeout=1500 enabled=this.vimEnabled}}
    {{useHotkeys this.arrowSequences}}

    <div class='app'>
      <header>
        <h1>Sequences with useHotkeys</h1>
        <p>
          Register several sequences, such as Vim commands, in one useHotkeys
          call. Each key must follow the previous one within the timeout.
        </p>
      </header>

      <main>
        <section class='demo-section'>
          <h2>Vim-style commands</h2>
          <label>
            <input
              type='checkbox'
              checked={{this.vimEnabled}}
              {{on 'change' this.toggleVim}}
            />
            Enable Vim commands
          </label>
          <p>
            Press
            <kbd>{{this.formatForDisplay (array 'G' 'G')}}</kbd>,
            <kbd>{{this.formatForDisplay 'Shift+G'}}</kbd>,
            <kbd>{{this.formatForDisplay (array 'D' 'D')}}</kbd>,
            <kbd>{{this.formatForDisplay (array 'D' 'W')}}</kbd>, or
            <kbd>{{this.formatForDisplay (array 'C' 'I' 'W')}}</kbd>, with up
            to 1.5 seconds between keys.
          </p>
          <p role='status'>Last command: {{this.lastCommand}}</p>
        </section>

        <section class='demo-section'>
          <h2>Check one definition with defineHotkey</h2>
          <p>
            Press
            <kbd>{{this.formatForDisplay
                (array 'ArrowUp' 'ArrowUp' 'ArrowDown' 'ArrowDown')
              }}</kbd>
            or
            <kbd>{{this.formatForDisplay
                (array 'ArrowLeft' 'ArrowRight' 'ArrowLeft' 'ArrowRight')
              }}</kbd>.
          </p>
          <p role='status'>Konami code: {{this.konamiCount}}{{#if this.konamiSteps}} ({{this.konamiSteps}} steps){{/if}}, Side to side: {{this.sideCount}}</p>
        </section>

        <section class='demo-section'>
          <h2>List the registrations</h2>
          <p role='status'>{{this.registrations.hotkeys.length}} hotkeys registered</p>
          <table class='registrations-table'>
            <thead>
              <tr>
                <th>Hotkey</th>
                <th>Name</th>
                <th>Progress</th>
                <th>Fired</th>
              </tr>
            </thead>
            <tbody>
              {{#each this.registrations.hotkeys key='id' as |reg|}}
                <tr>
                  <td><kbd>{{this.formatForDisplay reg.hotkey}}</kbd></td>
                  <td>{{reg.options.meta.name}}</td>
                  <td>{{progress reg}}</td>
                  <td>{{reg.triggerCount}}</td>
                </tr>
              {{/each}}
            </tbody>
          </table>
        </section>
      </main>
    </div>
  </template>
}