Skip to content

Ember Example: UseHotkeys

import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import { fn } from '@ember/helper'
import { on } from '@ember/modifier'
import {
  defineHotkey,
  findHotkeyConflicts,
  normalizeHotkey,
  useFormatForDisplay,
  useHotkeyRegistrations,
  useHotkeys,
  validateHotkey,
} from '@tanstack/ember-hotkeys'
import type {
  EmberHotkeyDefinition,
  Hotkey,
  HotkeyIssue,
} from '@tanstack/ember-hotkeys'

export default class App extends Component {
  <template>
    <div class='app'>
      <header>
        <h1>useHotkeys</h1>
        <p>
          Register a list of hotkeys in one helper call. The list can change
          length between renders.
        </p>
      </header>
      <main>
        <RegisterMultipleHotkeys />
        <DefineHotkeyDemo />
        <SharedOptionsDemo />
        <ListFromDataDemo />
        <RegistrationsTable />
      </main>
    </div>
  </template>
}

class RegisterMultipleHotkeys extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked save = 0
  @tracked undo = 0
  @tracked redo = 0

  // `meta` doesn't change matching. The registrations table below and the
  // devtools read it to name each hotkey.
  shortcuts: Array<EmberHotkeyDefinition> = [
    {
      hotkey: 'Shift+S',
      callback: () => this.save++,
      options: { meta: { name: 'Save', description: 'Save the document' } },
    },
    {
      hotkey: 'Shift+U',
      callback: () => this.undo++,
      options: { meta: { name: 'Undo', description: 'Undo the last action' } },
    },
    {
      hotkey: 'Shift+R',
      callback: () => this.redo++,
      options: {
        meta: { name: 'Redo', description: 'Redo the last undone action' },
      },
    },
  ]

  <template>
    {{useHotkeys this.shortcuts}}
    <section class='demo-section'>
      <h2>Register multiple hotkeys</h2>
      <div class='hotkey-grid'>
        <div>
          <kbd>{{this.formatForDisplay 'Shift+S'}}</kbd>
          Save
        </div>
        <div>
          <kbd>{{this.formatForDisplay 'Shift+U'}}</kbd>
          Undo
        </div>
        <div>
          <kbd>{{this.formatForDisplay 'Shift+R'}}</kbd>
          Redo
        </div>
      </div>
      <p role='status'>Save: {{this.save}}, Undo: {{this.undo}}, Redo: {{this.redo}}</p>
    </section>
  </template>
}

class DefineHotkeyDemo extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked pinCount = 0
  @tracked pinModifiers = ''

  // useHotkeys gives every array item one type that fits any hotkey, so an
  // item's callback `context` can be a chord or a sequence, and reading
  // `context.parsedChord` needs a `context.kind` check first. defineHotkey
  // types one definition by its hotkey and returns it unchanged. Use it for
  // a definition you keep in a variable.
  pin = defineHotkey({
    hotkey: 'Shift+P',
    // Shift+P is a chord, so `context.parsedChord` needs no kind check.
    callback: (_event, context) => {
      this.pinCount++
      this.pinModifiers = context.parsedChord.modifiers.join('+')
    },
    // Chords only: holding Shift+P fires once. Without `requireReset`, key
    // repeat fires it again for as long as the keys are held. `timeout` here
    // would be a type error, because it applies only to sequences.
    options: { requireReset: true, meta: { name: 'Pin' } },
  })

  // A defined hotkey and an inline item can share one array.
  shortcuts: Array<EmberHotkeyDefinition> = [
    this.pin,
    {
      hotkey: 'Shift+O',
      callback: () => {
        this.pinCount = 0
        this.pinModifiers = ''
      },
      options: { meta: { name: 'Clear pins' } },
    },
  ]

  <template>
    {{useHotkeys this.shortcuts}}
    <section class='demo-section'>
      <h2>Check one definition with defineHotkey</h2>
      <p>
        Hold
        <kbd>{{this.formatForDisplay 'Shift+P'}}</kbd>
        to pin once. Press
        <kbd>{{this.formatForDisplay 'Shift+O'}}</kbd>
        to clear.
      </p>
      <p role='status'>Pins: {{this.pinCount}}{{#if this.pinModifiers}}, modifiers: {{this.pinModifiers}}{{/if}}</p>
    </section>
  </template>
}

class SharedOptionsDemo extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked enabled = true
  @tracked a = 0
  @tracked b = 0
  @tracked c = 0
  toggleEnabled = (event: Event) =>
    (this.enabled = (event.target as HTMLInputElement).checked)

  // `Alt+[KeyJ]` names the physical J key. On macOS, Option+J types ∆, so a
  // plain `Alt+J` depends on what the layout types there.
  shortcuts: Array<EmberHotkeyDefinition> = [
    {
      hotkey: 'Alt+[KeyJ]',
      callback: () => this.a++,
      options: { meta: { name: 'Action A' } },
    },
    {
      hotkey: 'Alt+[KeyK]',
      callback: () => this.b++,
      options: { meta: { name: 'Action B' } },
    },
    {
      hotkey: 'Alt+[KeyL]',
      callback: () => this.c++,
      options: { enabled: true, meta: { name: 'Action C' } },
    },
  ]

  <template>
    {{! Named arguments hold options for every item, and an item's own
        options win. Unchecking the box disables Action A and Action B.
        Action C sets enabled: true itself, so it keeps firing. }}
    {{useHotkeys this.shortcuts enabled=this.enabled}}
    <section class='demo-section'>
      <h2>Share options</h2>
      <label>
        <input
          type='checkbox'
          checked={{this.enabled}}
          {{on 'change' this.toggleEnabled}}
        />
        Enable shared hotkeys
      </label>
      <div class='hotkey-grid'>
        <div>
          <kbd>{{this.formatForDisplay 'Alt+[KeyJ]'}}</kbd>
          Action A
        </div>
        <div>
          <kbd>{{this.formatForDisplay 'Alt+[KeyK]'}}</kbd>
          Action B
        </div>
        <div>
          <kbd>{{this.formatForDisplay 'Alt+[KeyL]'}}</kbd>
          Action C (always on)
        </div>
      </div>
      <p role='status'>Action A: {{this.a}}, Action B: {{this.b}}, Action C: {{this.c}}</p>
    </section>
  </template>
}

// validateHotkey returns reason codes, so the app writes the messages.
const issueText = ({ reason, part }: HotkeyIssue) =>
  ({
    empty: 'Enter a hotkey.',
    'empty-part': 'Remove the empty part between + signs.',
    'unknown-modifier': `Unknown modifier ${part}.`,
    'invalid-physical-key': `${part} isn't a physical key code.`,
    'modifier-only': `Add a key after ${part}.`,
    'unknown-key': `Unknown key ${part}. Key names are case-sensitive.`,
  })[reason]

let nextId = 3

class ListFromDataDemo extends Component {
  formatForDisplay = useFormatForDisplay()
  @tracked shortcuts: Array<{
    id: number
    hotkey: Hotkey
    name: string
    count: number
  }> = [
    { id: 0, hotkey: 'Shift+A', name: 'Action 1', count: 0 },
    { id: 1, hotkey: 'Shift+B', name: 'Action 2', count: 0 },
    { id: 2, hotkey: 'Shift+C', name: 'Action 3', count: 0 },
  ]
  @tracked newHotkey = ''
  @tracked newName = ''
  @tracked message = 'Add a hotkey to the list.'

  // The only place in this example that maps data into the call. The list
  // comes from the user, so its hotkeys aren't known when the code is
  // written, and useHotkeys takes an array of any length. A getter that
  // reads tracked state updates the registrations when the list changes.
  // useHotkeys matches items by index, so removing one re-registers the
  // items after it, and their counts in the table below start over.
  get definitions(): Array<EmberHotkeyDefinition> {
    return this.shortcuts.map((s) => ({
      hotkey: s.hotkey,
      callback: () => {
        this.shortcuts = this.shortcuts.map((item) =>
          item.id === s.id ? { ...item, count: item.count + 1 } : item,
        )
      },
      options: { meta: { name: s.name } },
    }))
  }

  updateHotkey = (event: Event) =>
    (this.newHotkey = (event.target as HTMLInputElement).value)
  updateName = (event: Event) =>
    (this.newName = (event.target as HTMLInputElement).value)
  remove = (id: number) => {
    this.shortcuts = this.shortcuts.filter((item) => item.id !== id)
  }

  addShortcut = (event: SubmitEvent) => {
    event.preventDefault()
    const name = this.newName.trim()
    if (!name) {
      this.message = 'Enter a name.'
      return
    }
    // Check the text before registering it. Invalid text doesn't register,
    // and an unknown key, such as a lowercase `escape`, registers but never
    // fires. Both fail silently in production.
    const validation = validateHotkey(this.newHotkey.trim())
    const issues = [...validation.errors, ...validation.warnings]
    if (issues.length > 0) {
      this.message = issues.map(issueText).join(' ')
      return
    }
    const hotkey = normalizeHotkey(this.newHotkey.trim())
    // findHotkeyConflicts lists live registrations that the new hotkey would
    // duplicate. Without this check, the duplicate registers anyway, both
    // callbacks run, and the library logs a warning in development.
    const conflicts = findHotkeyConflicts(hotkey)
    if (conflicts.length > 0) {
      this.message = `Already used by ${conflicts[0]?.registration.options.meta?.name ?? 'another hotkey'}.`
      return
    }
    this.shortcuts = [
      ...this.shortcuts,
      { id: nextId++, hotkey, name, count: 0 },
    ]
    this.message = `Added ${name}.`
    this.newHotkey = ''
    this.newName = ''
  }

  <template>
    {{useHotkeys this.definitions}}
    <section class='demo-section'>
      <h2>Build the list from data</h2>
      <ul class='dynamic-list'>
        {{#each this.shortcuts key='id' as |s|}}
          <li class='dynamic-item'>
            <kbd>{{this.formatForDisplay s.hotkey}}</kbd>
            <span>{{s.name}}</span>
            <span class='count'>Fired {{s.count}}</span>
            <button type='button' {{on 'click' (fn this.remove s.id)}}>
              Remove
            </button>
          </li>
        {{/each}}
      </ul>
      <form class='add-form' {{on 'submit' this.addShortcut}}>
        <label>
          Hotkey
          <input
            value={{this.newHotkey}}
            placeholder='Shift+D'
            {{on 'input' this.updateHotkey}}
          />
        </label>
        <label>
          Name
          <input
            value={{this.newName}}
            placeholder='Action 4'
            {{on 'input' this.updateName}}
          />
        </label>
        <button type='submit'>Add</button>
      </form>
      <p role='status'>{{this.message}}</p>
    </section>
  </template>
}

class RegistrationsTable extends Component {
  formatForDisplay = useFormatForDisplay()
  // Every registration on the page, chords and sequences. It updates when a
  // hotkey registers, unregisters, changes `enabled`, or fires.
  registrations = useHotkeyRegistrations(this)

  <template>
    <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>Status</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>{{reg.status}}</td>
              <td>{{reg.triggerCount}}</td>
            </tr>
          {{/each}}
        </tbody>
      </table>
    </section>
  </template>
}