Skip to content

Ember Example: UseHotkeyRecorder Sequences

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

// A recorded hotkey as text: `Mod+S` for a chord, `G H` for a sequence. A
// sequence is an array of chords, such as `['G', 'H']`.
function hotkeyText(hotkey: Hotkey) {
  return Array.isArray(hotkey) ? hotkey.join(' ') : hotkey
}

export default class App extends Component {
  <template>
    <div class='app'>
      <header>
        <h1>Recording Sequences</h1>
        <p>
          With
          <code>maxSteps</code>
          above 1,
          <code>useHotkeyRecorder</code>
          records several chords in a row, such as G then I. Each section
          shows one recorder option.
        </p>
      </header>

      <main>
        <ShortcutList />
        <MaxSteps />
        <CommitKeys />
        <IdleTimeout />
        <Validation />
        <Conflicts />
      </main>
    </div>
  </template>
}

class ShortcutList extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'
  @tracked editing: string | null = null
  @tracked shortcuts: Array<{ name: string; hotkey: Hotkey | null }> = [
    { name: 'Save', hotkey: 'Mod+S' },
    { name: 'Go to inbox', hotkey: ['G', 'I'] },
    { name: 'Go to settings', hotkey: ['G', 'S'] },
  ]

  // With `maxSteps: Infinity`, each chord adds a step and Enter saves. One
  // step saves as a chord string such as 'Mod+S'; two or more save as a
  // sequence such as ['G', 'H']. Backspace removes the last step, and on an
  // empty recording calls `onClear`. Escape cancels. The callbacks read
  // `this.editing` when they run, so they see the current row.
  recorder = useHotkeyRecorder(this, {
    maxSteps: Infinity,
    onRecord: (hotkey) => {
      this.shortcuts = this.shortcuts.map((s) =>
        s.name === this.editing ? { ...s, hotkey } : s,
      )
      this.status = `${this.editing} is now ${hotkeyText(hotkey)}`
      this.editing = null
    },
    onCancel: () => {
      this.status = `${this.editing} unchanged`
      this.editing = null
    },
    // The recorder only reports the clear; this app decides that clearing
    // unbinds the shortcut.
    onClear: () => {
      this.shortcuts = this.shortcuts.map((s) =>
        s.name === this.editing ? { ...s, hotkey: null } : s,
      )
      this.status = `${this.editing} cleared`
      this.editing = null
    },
  })

  // The shortcuts are user data held in tracked state, so mapping them into
  // one `useHotkeys` list is the point here. Chords and sequences register
  // the same way, and a null hotkey registers nothing. Mod+S would open the
  // browser's Save dialog; a matched hotkey calls `preventDefault` by
  // default. While any recorder is recording, these hotkeys pause.
  get definitions(): Array<EmberHotkeyDefinition> {
    return this.shortcuts.map((s) => ({
      hotkey: s.hotkey,
      callback: () => (this.status = `Ran ${s.name}`),
      options: { meta: { name: s.name } },
    }))
  }

  isRecordingRow = (name: string) =>
    this.editing === name && this.recorder.isRecording

  edit = (name: string) => {
    // Starting while already recording does nothing, so a click on another
    // row moves the recording to that row.
    this.recorder.startRecording()
    this.editing = name
    this.status = `Recording ${name}`
  }

  <template>
    {{useHotkeys this.definitions}}
    <section class='demo-section'>
      <h2>Shortcut list</h2>
      <p>
        Click Edit, press each chord in order, then press Enter. Backspace
        removes the last chord, or clears the shortcut when none are left.
        Escape cancels.
      </p>
      <ul class='shortcut-list'>
        {{#each this.shortcuts key='name' as |s|}}
          {{! The ~ marks trim whitespace, so the row's text has no spaces
              between its parts. }}
          <li><span>{{s.name}}</span>
            {{~#if (this.isRecordingRow s.name)~}}
              {{~#if this.recorder.steps.length~}}
                <kbd>{{this.formatForDisplay this.recorder.steps}}</kbd>
              {{~else~}}
                <span>Press keys</span>
              {{~/if~}}
            {{~else if s.hotkey~}}
              <kbd>{{this.formatForDisplay s.hotkey}}</kbd>
            {{~else~}}
              <span>No shortcut</span>
            {{~/if~}}
            {{~#if (this.isRecordingRow s.name)~}}
              <button
                type='button'
                {{on 'click' this.recorder.cancelRecording}}
              >Cancel</button>
            {{~else~}}
              <button
                type='button'
                {{on 'click' (fn this.edit s.name)}}
              >Edit</button>
            {{~/if~}}
          </li>
        {{/each}}
      </ul>
      <p role='status' class='status'>{{this.status}}</p>
    </section>
  </template>
}

class MaxSteps extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'

  // Recording saves by itself when it reaches `maxSteps`, here the second
  // chord. Enter still saves a single chord before that.
  recorder = useHotkeyRecorder(this, {
    maxSteps: 2,
    onRecord: (hotkey) => (this.status = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  record = () => {
    this.recorder.startRecording()
    this.status = 'Recording'
  }

  <template>
    <section class='demo-section'>
      <h2>Max steps</h2>
      <p>
        Press
        <kbd>{{this.formatForDisplay 'G'}}</kbd>, then
        <kbd>{{this.formatForDisplay 'H'}}</kbd>. Recording ends at the second
        chord without Enter.
      </p>
      <div class='buttons'>
        <button type='button' {{on 'click' this.record}}>Record</button>
      </div>
      <p role='status' class='status'>{{this.status}}</p>
    </section>
  </template>
}

class CommitKeys extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'

  // The default, `commitKeys: 'enter'`: plain Enter saves the steps.
  enterSaves = useHotkeyRecorder(this, {
    maxSteps: Infinity,
    commitKeys: 'enter',
    onRecord: (hotkey) => (this.status = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  // With `commitKeys: 'none'`, Enter is recorded as a step, so a sequence
  // can end in Enter. Save with `commitRecording()`, `idleTimeoutMs`, or
  // `maxSteps` instead.
  enterRecords = useHotkeyRecorder(this, {
    maxSteps: Infinity,
    commitKeys: 'none',
    onRecord: (hotkey) => (this.status = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  // `steps` is tracked, so Done turns on with the first step.
  get nothingToCommit() {
    return this.enterRecords.steps.length === 0
  }

  recordEnterSaves = () => {
    this.enterSaves.startRecording()
    this.status = 'Recording'
  }

  recordEnterRecords = () => {
    this.enterRecords.startRecording()
    this.status = 'Recording'
  }

  <template>
    <section class='demo-section'>
      <h2>Commit keys</h2>
      <p>
        Press
        <kbd>{{this.formatForDisplay 'G'}}</kbd>, then
        <kbd>{{this.formatForDisplay 'Enter'}}</kbd>
        with each button. With commitKeys: 'none', click Done to save.
      </p>
      <div class='buttons'>
        <button type='button' {{on 'click' this.recordEnterSaves}}>Record (commitKeys: 'enter')</button>
        <button type='button' {{on 'click' this.recordEnterRecords}}>Record (commitKeys: 'none')</button>
        <button
          type='button'
          disabled={{this.nothingToCommit}}
          {{on 'click' this.enterRecords.commitRecording}}
        >Done</button>
      </div>
      {{#if this.enterRecords.steps.length}}
        <p>Steps: <kbd>{{this.formatForDisplay this.enterRecords.steps}}</kbd></p>
      {{/if}}
      <p role='status' class='status'>{{this.status}}</p>
    </section>
  </template>
}

class IdleTimeout extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'

  // Saves one second after the last chord, so the user doesn't need Enter.
  // Each new chord restarts the wait. Without it, a recording waits for
  // Enter or `maxSteps`.
  recorder = useHotkeyRecorder(this, {
    maxSteps: Infinity,
    idleTimeoutMs: 1000,
    onRecord: (hotkey) => (this.status = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  record = () => {
    this.recorder.startRecording()
    this.status = 'Recording'
  }

  <template>
    <section class='demo-section'>
      <h2>Idle timeout</h2>
      <p>
        Press
        <kbd>{{this.formatForDisplay 'G'}}</kbd>, then
        <kbd>{{this.formatForDisplay 'H'}}</kbd>, and wait one second.
      </p>
      <div class='buttons'>
        <button type='button' {{on 'click' this.record}}>Record</button>
      </div>
      {{#if this.recorder.steps.length}}
        <p>Steps: <kbd>{{this.formatForDisplay this.recorder.steps}}</kbd></p>
      {{/if}}
      <p role='status' class='status'>{{this.status}}</p>
    </section>
  </template>
}

class Validation extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'

  // `validate` runs when the recording saves. Check `context.kind` before
  // reading `parsedChord` (one step) or `parsedSequence` (two or more). A
  // rejected recording keeps its steps, so the user can add a chord or press
  // Backspace instead of starting over.
  recorder = useHotkeyRecorder(this, {
    maxSteps: Infinity,
    validate: (_hotkey, context) =>
      context.kind === 'sequence' ||
      context.parsedChord.modifiers.length > 0 ||
      'A single chord needs a modifier.',
    onReject: ({ reason, message }) =>
      (this.status = message ? `Rejected: ${message}` : `Rejected (${reason})`),
    onRecord: (hotkey) => (this.status = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  record = () => {
    this.recorder.startRecording()
    this.status = 'Recording'
  }

  <template>
    <section class='demo-section'>
      <h2>Validation</h2>
      <p>
        Press
        <kbd>{{this.formatForDisplay 'G'}}</kbd>, then
        <kbd>{{this.formatForDisplay 'Enter'}}</kbd>
        to see the rejection. Then press
        <kbd>{{this.formatForDisplay 'H'}}</kbd>
        and
        <kbd>{{this.formatForDisplay 'Enter'}}</kbd>.
      </p>
      <div class='buttons'>
        <button type='button' {{on 'click' this.record}}>Record</button>
      </div>
      {{#if this.recorder.steps.length}}
        <p>Steps: <kbd>{{this.formatForDisplay this.recorder.steps}}</kbd></p>
      {{/if}}
      <p role='status' class='status'>{{this.status}}</p>
    </section>
  </template>
}

class Conflicts extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'

  // `detectConflicts` rejects a recording that a rendered hotkey already
  // uses, including prefixes: a chord conflicts with a sequence that starts
  // with it, so `G` conflicts with G I. A sequence conflicts with a chord
  // equal to its first step. G H and G I don't conflict.
  recorder = useHotkeyRecorder(this, {
    maxSteps: Infinity,
    detectConflicts: true,
    onReject: ({ reason, hotkey, conflicts }) =>
      (this.status =
        reason === 'conflict' && hotkey
          ? `Rejected: ${hotkeyText(hotkey)} is used by ${conflicts
              ?.map((c) => c.registration.options.meta?.name)
              .join(', ')}`
          : `Rejected (${reason})`),
    onRecord: (hotkey) => (this.status = `Recorded ${hotkeyText(hotkey)}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  record = () => {
    this.recorder.startRecording()
    this.status = 'Recording'
  }

  <template>
    <section class='demo-section'>
      <h2>Conflicts</h2>
      <p>
        Record
        <kbd>{{this.formatForDisplay 'G'}}</kbd>
        alone, or
        <kbd>{{this.formatForDisplay (array 'G' 'I')}}</kbd>, to conflict with
        the list above. Then record
        <kbd>{{this.formatForDisplay (array 'G' 'H')}}</kbd>.
      </p>
      <div class='buttons'>
        <button type='button' {{on 'click' this.record}}>Record</button>
      </div>
      {{#if this.recorder.steps.length}}
        <p>Steps: <kbd>{{this.formatForDisplay this.recorder.steps}}</kbd></p>
      {{/if}}
      <p role='status' class='status'>{{this.status}}</p>
    </section>
  </template>
}