Skip to content

Ember Example: UseHeldKeys

import { hash } from '@ember/helper'
import { on } from '@ember/modifier'
import { schedule } from '@ember/runloop'
import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import { modifier } from 'ember-modifier'
import {
  useFormatForDisplay,
  useHeldKeyCodes,
  useHeldKeys,
  useHotkey,
  useHotkeyHint,
} from '@tanstack/ember-hotkeys'

class App extends Component {
  formatForDisplay = useFormatForDisplay()
  // Held keys in press order, such as ['Shift', 'A']. Updates on every
  // keydown and keyup, and empties when the window loses focus. Pass the
  // component, which owns the subscription.
  heldKeys = useHeldKeys(this)
  // Each held key's physical `event.code`, such as { Shift: 'ShiftLeft' }.
  heldCodes = useHeldKeyCodes(this)

  // True while the user holds Mod, and the Mod+S below can fire. The hint
  // registers nothing: it reads the held keys and the registrations.
  saveHint = useHotkeyHint(this, 'Mod+S')
  // False while Bold is disabled, even with Mod held, because no enabled
  // registration of Mod+B can fire.
  boldHint = useHotkeyHint(this, 'Mod+B')
  // True while the user holds Mod, Shift, or both. Holding a modifier the
  // hotkey doesn't use, such as Alt, hides it.
  exportHint = useHotkeyHint(this, 'Mod+Shift+E')
  // With `exact: true`, only Mod and Shift held together show the hint.
  // Without it, Mod or Shift alone would show it, as for Export.
  archiveHint = useHotkeyHint(this, 'Mod+Shift+A', { exact: true })

  @tracked history: Array<string> = []
  @tracked lastAction = 'none'
  @tracked boldEnabled = true

  save = () => (this.lastAction = 'Save')
  bold = () => (this.lastAction = 'Bold')
  export = () => (this.lastAction = 'Export')
  archive = () => (this.lastAction = 'Archive')
  setBoldEnabled = (event: Event) =>
    (this.boldEnabled = (event.target as HTMLInputElement).checked)
  clearHistory = () => (this.history = [])

  get heldText() {
    const keys = this.heldKeys.value
    return keys.length > 0 ? `Held: ${keys.join(' + ')}` : 'No keys held'
  }

  get heldCodesText() {
    const keys = this.heldKeys.value
    return keys.length > 0
      ? keys.map((key) => `${key}: ${this.heldCodes.value[key]}`).join(', ')
      : 'No keys held'
  }

  get hintsText() {
    const shown = [
      this.saveHint.value && 'Save',
      this.boldHint.value && 'Bold',
      this.exportHint.value && 'Export',
      this.archiveHint.value && 'Archive',
    ].filter(Boolean)
    return shown.length > 0
      ? `Hints shown: ${shown.join(', ')}`
      : 'Hints shown: none'
  }

  get historyText() {
    const count = this.history.length
    return `Recorded ${count} ${count === 1 ? 'combination' : 'combinations'}`
  }

  // Once every key is released, records the most keys held at once, such as
  // 'Shift + Control + A', and keeps the last 10. The modifier runs again
  // each time the held keys change.
  mostHeld: Array<string> = []
  recordHistory = modifier((_element, [heldKeys]: [Array<string>]) => {
    if (heldKeys.length > this.mostHeld.length) this.mostHeld = heldKeys
    if (heldKeys.length > 0 || this.mostHeld.length === 0) return
    const combination = this.mostHeld.join(' + ')
    this.mostHeld = []
    // After this render, because the list rendered from `history` already.
    schedule('afterRender', () => {
      this.history = [...this.history.slice(-9), combination]
    })
  })

  <template>
    {{! Mod+S would open the browser's Save dialog. A matched hotkey calls
        `preventDefault` by default, so the page handles it instead. }}
    {{useHotkey 'Mod+S' this.save}}
    {{! While `enabled` is false, Mod+B doesn't fire, and its hint stays
        hidden. }}
    {{useHotkey 'Mod+B' this.bold enabled=this.boldEnabled}}
    {{useHotkey 'Mod+Shift+E' this.export}}
    {{useHotkey 'Mod+Shift+A' this.archive}}

    <div class='app'>
      <header>
        <h1>useHeldKeys</h1>
        <p>
          Track which keys the user is holding, and show a hotkey's label only
          while its modifiers are held.
        </p>
      </header>

      <main>
        <section class='demo-section'>
          <h2>Held keys</h2>
          <p>
            Hold
            <kbd>Shift</kbd>
            +
            <kbd>Control</kbd>
            +
            <kbd>A</kbd>, or press several letters at once, then release them
            one by one.
          </p>
          {{! `(hash key=key)` formats a raw `event.key` value, such as
              'Control' as ⌃ on macOS. }}
          <div class='key-display' aria-hidden='true'>
            {{#each this.heldKeys.value as |key|}}
              <kbd class='large'>{{this.formatForDisplay (hash key=key)}}</kbd>
            {{/each}}
          </div>
          <p role='status'>{{this.heldText}}</p>
        </section>

        <section class='demo-section'>
          <h2>Held key codes</h2>
          <p>
            The physical key behind each held key. Left and right
            <kbd>Shift</kbd>
            both hold
            <code>Shift</code>, with different codes.
          </p>
          <p role='status'>{{this.heldCodesText}}</p>
        </section>

        <section class='demo-section'>
          <h2>Hotkey hints</h2>
          <p>
            Hold
            <kbd>{{this.formatForDisplay 'Mod'}}</kbd>,
            <kbd>Shift</kbd>, or both to see which shortcuts they lead to.
          </p>
          <div class='toolbar'>
            <button type='button' {{on 'click' this.save}}>
              Save
              {{#if this.saveHint.value}}
                <kbd>{{this.formatForDisplay 'Mod+S'}}</kbd>
              {{/if}}
            </button>
            <button type='button' {{on 'click' this.bold}}>
              Bold
              {{#if this.boldHint.value}}
                <kbd>{{this.formatForDisplay 'Mod+B'}}</kbd>
              {{/if}}
            </button>
            <button type='button' {{on 'click' this.export}}>
              Export
              {{#if this.exportHint.value}}
                <kbd>{{this.formatForDisplay 'Mod+Shift+E'}}</kbd>
              {{/if}}
            </button>
            <button type='button' {{on 'click' this.archive}}>
              Archive
              {{#if this.archiveHint.value}}
                <kbd>{{this.formatForDisplay 'Mod+Shift+A'}}</kbd>
              {{/if}}
            </button>
          </div>
          <label>
            <input
              type='checkbox'
              checked={{this.boldEnabled}}
              {{on 'change' this.setBoldEnabled}}
            />
            Enable Bold
          </label>
          <p>Last action: {{this.lastAction}}</p>
          <p role='status'>{{this.hintsText}}</p>
        </section>

        <section class='demo-section'>
          <h2>Recent combinations</h2>
          <p>
            Each entry is the most keys you held at once, added when you release
            them all.
          </p>
          <p role='status'>{{this.historyText}}</p>
          <ol class='history-list' {{this.recordHistory this.heldKeys.value}}>
            {{#each this.history as |combination|}}
              <li>{{combination}}</li>
            {{/each}}
          </ol>
          <button type='button' {{on 'click' this.clearHistory}}>
            Clear history
          </button>
        </section>
      </main>
    </div>
  </template>
}
export default App