Skip to content

Ember Example: UseHotkeyRecorder

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

export default class App extends Component {
  <template>
    <div class='app'>
      <header>
        <h1>Hotkey Recorder</h1>
        <p>
          <code>useHotkeyRecorder</code>
          records the next key combination the user presses. Each section
          shows one recorder option.
        </p>
      </header>

      <main>
        <ShortcutList />
        <Validation />
        <Conflicts />
        <RecordBy />
        <CancelOnBlur />
        <RecordTab />
      </main>
    </div>
  </template>
}

class ShortcutList extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'
  @tracked editing: string | null = null
  @tracked shortcuts: Array<{ name: string; hotkey: HotkeyChord | null }> = [
    { name: 'Save', hotkey: 'Mod+S' },
    { name: 'Open', hotkey: 'Mod+O' },
    { name: 'Toggle sidebar', hotkey: 'Mod+B' },
  ]

  // One recorder serves every row; `editing` says which row it records for.
  // The callbacks read `this.editing` when they run, so they see the current
  // row. With the default `maxSteps: 1`, the first chord the user presses
  // ends the recording.
  recorder = useHotkeyRecorder(this, {
    onRecord: (hotkey) => {
      this.shortcuts = this.shortcuts.map((s) =>
        s.name === this.editing ? { ...s, hotkey } : s,
      )
      this.status = `${this.editing} is now ${hotkey}`
      this.editing = null
    },
    // Escape, `cancelRecording()`, Tab, or the window losing focus. The old
    // shortcut stays.
    onCancel: () => {
      this.status = `${this.editing} unchanged`
      this.editing = null
    },
    // Backspace or Delete. The recorder only reports it; 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. A null hotkey registers nothing.
  // Mod+S and Mod+O would open the browser's Save and Open dialogs; a matched
  // hotkey calls `preventDefault` by default. While any recorder is
  // recording, these hotkeys pause, so recording Mod+S doesn't also run Save.
  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, then press a key combination. Escape cancels and keeps the
        old shortcut. Backspace or Delete clears it.
      </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)~}}
              <span>Press keys</span>
            {{~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 Validation extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'

  // Return true to accept, or a message to reject. A rejected chord keeps
  // the recorder listening for another one, and `onReject` gets the message.
  recorder = useHotkeyRecorder(this, {
    validate: (_hotkey, { parsedChord }) =>
      parsedChord.modifiers.length > 0 ||
      'Include a modifier, such as Mod or Alt.',
    onReject: ({ reason, message }) =>
      (this.status = message ? `Rejected: ${message}` : `Rejected (${reason})`),
    onRecord: (hotkey) => (this.status = `Recorded ${hotkey}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

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

  <template>
    <section class='demo-section'>
      <h2>Validation</h2>
      <p>
        This recorder rejects a key without a modifier. Press
        <kbd>{{this.formatForDisplay 'K'}}</kbd>, then
        <kbd>{{this.formatForDisplay 'Mod+Shift+K'}}</kbd>.
      </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 Conflicts extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'

  runPalette = () => (this.status = 'Ran Command palette')

  // `detectConflicts` rejects a chord that a rendered hotkey already uses,
  // including the ones in the shortcut list above. Each conflict carries the
  // registration, so its `meta.name` can name the owner. Without it, the
  // recorder accepts the chord and two hotkeys fire on the same press.
  recorder = useHotkeyRecorder(this, {
    detectConflicts: true,
    onReject: ({ reason, hotkey, conflicts }) =>
      (this.status =
        reason === 'conflict'
          ? `Rejected: ${hotkey} is used by ${conflicts
              ?.map((c) => c.registration.options.meta?.name)
              .join(', ')}`
          : `Rejected (${reason})`),
    onRecord: (hotkey) => (this.status = `Recorded ${hotkey}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

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

  <template>
    {{useHotkey 'Mod+K' this.runPalette meta=(hash name='Command palette')}}
    <section class='demo-section'>
      <h2>Conflicts</h2>
      <p>
        This section registers
        <kbd>{{this.formatForDisplay 'Mod+K'}}</kbd>
        for a command palette. Record it, or
        <kbd>{{this.formatForDisplay 'Mod+S'}}</kbd>
        from the list above, to see the conflict. Then record
        <kbd>{{this.formatForDisplay 'Mod+J'}}</kbd>.
      </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 RecordBy extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked status = 'Not recording'

  // The default. Writes what the press typed, the way you'd write the hotkey
  // by hand: Shift+/ records `?`, which matches wherever the user's layout
  // types `?`. (`recordBy: 'key'` also writes the typed character, even for
  // macOS Option+S, which types `ß`.)
  byTypedKey = useHotkeyRecorder(this, {
    recordBy: 'auto',
    onRecord: (hotkey) => (this.status = `Recorded ${hotkey}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  // Writes the physical key: Shift+/ records `Shift+[Slash]`, which matches
  // that key position on every layout, whatever it types.
  byPosition = useHotkeyRecorder(this, {
    recordBy: 'code',
    onRecord: (hotkey) => (this.status = `Recorded ${hotkey}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  recordTypedKey = () => {
    this.byTypedKey.startRecording()
    this.status = 'Recording'
  }

  recordPosition = () => {
    this.byPosition.startRecording()
    this.status = 'Recording'
  }

  <template>
    <section class='demo-section'>
      <h2>Record by</h2>
      <p>
        Press
        <kbd>{{this.formatForDisplay 'Shift+[Slash]'}}</kbd>
        with each button to compare what gets saved.
      </p>
      <div class='buttons'>
        <button type='button' {{on 'click' this.recordTypedKey}}>Record what it types</button>
        <button type='button' {{on 'click' this.recordPosition}}>Record key position</button>
      </div>
      <p role='status' class='status'>{{this.status}}</p>
    </section>
  </template>
}

class CancelOnBlur extends Component {
  @tracked status = 'Not recording'

  // By default, recording cancels when the window loses focus, as when the
  // user switches apps or tabs. Keys pressed elsewhere never reach the page,
  // so the recorder would otherwise wait for a press that isn't coming.
  cancelsOnBlur = useHotkeyRecorder(this, {
    onRecord: (hotkey) => (this.status = `Recorded ${hotkey}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  // With `cancelOnBlur: false`, recording waits until the user comes back.
  keepsRecording = useHotkeyRecorder(this, {
    cancelOnBlur: false,
    onRecord: (hotkey) => (this.status = `Recorded ${hotkey}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  recordDefault = () => {
    this.cancelsOnBlur.startRecording()
    this.status = 'Recording'
  }

  recordKeep = () => {
    this.keepsRecording.startRecording()
    this.status = 'Recording'
  }

  <template>
    <section class='demo-section'>
      <h2>Cancel on blur</h2>
      <p>
        Start recording, switch to another app or tab, then come back and
        press a key combination.
      </p>
      <div class='buttons'>
        <button type='button' {{on 'click' this.recordDefault}}>Record (default)</button>
        <button type='button' {{on 'click' this.recordKeep}}>Record (cancelOnBlur: false)</button>
      </div>
      <p role='status' class='status'>{{this.status}}</p>
    </section>
  </template>
}

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

  // By default, Tab and Shift+Tab cancel recording and move focus as usual,
  // so a keyboard user can leave the recorder.
  tabLeaves = useHotkeyRecorder(this, {
    onRecord: (hotkey) => (this.status = `Recorded ${hotkey}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  // With `recordTab: true`, Tab and Shift+Tab are recorded like any other
  // chord, and only Escape cancels. Tell users so, as the text below does.
  tabRecords = useHotkeyRecorder(this, {
    recordTab: true,
    onRecord: (hotkey) => (this.status = `Recorded ${hotkey}`),
    onCancel: () => (this.status = 'Cancelled'),
  })

  recordDefault = () => {
    this.tabLeaves.startRecording()
    this.status = 'Recording'
  }

  recordTabKey = () => {
    this.tabRecords.startRecording()
    this.status = 'Recording'
  }

  <template>
    <section class='demo-section'>
      <h2>Record Tab</h2>
      <p>
        Start recording and press
        <kbd>{{this.formatForDisplay 'Tab'}}</kbd>
        or
        <kbd>{{this.formatForDisplay 'Shift+Tab'}}</kbd>. With recordTab,
        press
        <kbd>{{this.formatForDisplay 'Escape'}}</kbd>
        to cancel.
      </p>
      <div class='buttons'>
        <button type='button' {{on 'click' this.recordDefault}}>Record (default)</button>
        <button type='button' {{on 'click' this.recordTabKey}}>Record (recordTab: true)</button>
      </div>
      <p role='status' class='status'>{{this.status}}</p>
    </section>
  </template>
}