Skip to content

Ember Example: App Hotkeys

import { concat, fn, hash } from '@ember/helper'
import { on } from '@ember/modifier'
import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import {
  defineAppHotkeys,
  provideAppHotkeys,
  useAppHotkeyList,
  useAppHotkeys,
  useCustomHotkeys,
  useFormatForDisplay,
  useHotkey,
  useHotkeyRecorder,
  useHotkeyRegistrations,
} from '@tanstack/ember-hotkeys'
import type {
  AppHotkey,
  AppHotkeyId,
  HotkeyRegistrationView,
  RegisteredAppHotkeyListItem,
} from '@tanstack/ember-hotkeys'

// A large app can declare hotkeys next to the feature that owns them, then
// spread them into the one object it provides. Each entry keeps its id and
// the kind of its default, so `timeout` stays a sequence option here.
const navigationHotkeys = defineAppHotkeys({
  'nav.inbox': {
    hotkey: ['G', 'I'],
    meta: {
      name: 'Go to inbox',
      description: 'Press G, then I',
      group: 'Navigation',
    },
    // Sequences only. Without it, each key must follow within 1000 ms.
    options: { timeout: 1500 },
  },
})

// Every hotkey in the app, declared once. The keys ('doc.save') are ids:
// saved custom hotkeys refer to them, so keep them stable. The guide puts
// this in its own module that loads with the app shell; it lives here so the
// whole example is in one file.
const appHotkeys = defineAppHotkeys({
  'doc.save': {
    hotkey: 'Mod+S',
    meta: { name: 'Save', description: 'Saves the note', group: 'Document' },
    // Chords only. Without it, holding Mod+S saves again on every key repeat.
    // Mod+S would open the browser's Save dialog; a matched hotkey calls
    // `preventDefault` by default.
    options: { requireReset: true },
  },
  'doc.publish': {
    hotkey: 'Mod+Enter',
    meta: {
      name: 'Publish',
      description: 'Works only while the note has text',
      group: 'Document',
    },
  },
  // `null` declares an action with no default hotkey. It registers nothing
  // until the user assigns one.
  'doc.archive': {
    hotkey: null,
    meta: {
      name: 'Archive',
      description: 'No default hotkey',
      group: 'Document',
    },
  },
  ...navigationHotkeys,
})

// Types `useAppHotkeys()`, `useCustomHotkeys()`, and saved custom hotkeys by
// the ids above, so a misspelled id is a type error.
declare module '@tanstack/ember-hotkeys' {
  interface Register {
    appHotkeys: typeof appHotkeys
  }
}

// Ember has no provider component, so publish the app hotkeys before the app
// renders. This module loads with the app, so it runs first.
// `customHotkeys` is the user's saved changes, read once here.
// `onCustomHotkeysChange` gets every change, ready to save. Your app owns
// storage, so swap localStorage for a server without other changes.
provideAppHotkeys(appHotkeys, {
  customHotkeys: JSON.parse(
    localStorage.getItem('tanstack-hotkeys-app-hotkeys') ?? '{}',
  ),
  onCustomHotkeysChange: (customHotkeys) =>
    localStorage.setItem(
      'tanstack-hotkeys-app-hotkeys',
      JSON.stringify(customHotkeys),
    ),
})

const eq = (a: unknown, b: unknown) => a === b
const or = <T, U>(a: T, b: U) => a || b
const not = (a: unknown) => !a

class App extends Component {
  // The effective app hotkeys: the user's custom hotkey for each id, or the
  // default. Read them for labels; the declared `appHotkeys` object only has
  // the defaults.
  appHotkeys = useAppHotkeys(this)
  formatForDisplay = useFormatForDisplay()
  // Mounted registrations of every hotkey, including call-site meta.
  registrations = useHotkeyRegistrations(this)
  // Every app hotkey, mounted or not, in declaration order.
  appHotkeyList = useAppHotkeyList(this)
  customHotkeys = useCustomHotkeys(this)

  @tracked lastAction = ''
  @tracked published = ''
  @tracked toolbarResult = ''
  @tracked editing: AppHotkeyId | null = null
  @tracked message = 'No changes'

  // Template paths can't index ids that contain dots, so read app hotkeys
  // through getters.
  get saveHotkey() {
    return this.appHotkeys.value['doc.save']
  }
  get publishHotkey() {
    return this.appHotkeys.value['doc.publish']
  }
  get archiveHotkey() {
    return this.appHotkeys.value['doc.archive']
  }
  get inboxHotkey() {
    return this.appHotkeys.value['nav.inbox']
  }

  label = (hotkey: AppHotkey['hotkey']) =>
    (hotkey && this.formatForDisplay(hotkey)) || 'Unassigned'

  save = () => (this.lastAction = 'Save')
  goToInbox = () => (this.lastAction = 'Go to inbox')
  archive = () => (this.lastAction = 'Archive')

  // Reads the textarea, which nothing binds, so typing doesn't render again.
  // Ember has no built-in element ref, so it looks the element up by id.
  note = () =>
    (document.getElementById('note') as HTMLTextAreaElement | null)?.value.trim() ??
    ''
  // A getter is read on each key press and on `trigger()`. A plain boolean
  // would need tracked state that renders again on every keystroke.
  hasNote = () => !!this.note()
  publish = () => (this.published = this.note())

  get publishedText() {
    return this.published ? `Published: ${this.published}` : 'Nothing published'
  }

  // Only registrations of app hotkeys. A registration's meta includes
  // call-site meta, so Publish shows as "Publish note".
  get appHotkeyRegistrations() {
    return this.registrations.hotkeys.filter(
      (reg) => reg.options.appHotkeyId !== undefined,
    )
  }

  run = (reg: HotkeyRegistrationView) => {
    const name = reg.options.meta?.name
    this.toolbarResult = reg.trigger() ? `Ran: ${name}` : `Not run: ${name}`
  }

  get groups() {
    const items = this.appHotkeyList.value
    return [...new Set(items.map((item) => item.appHotkey.meta?.group))].map(
      (group) => ({
        group,
        items: items.filter((item) => item.appHotkey.meta?.group === group),
      }),
    )
  }

  get customizedText() {
    const items = this.appHotkeyList.value
    const customCount = items.filter((item) => item.isCustom).length
    return `Customized: ${customCount} of ${items.length}`
  }

  get saved() {
    return JSON.stringify(this.customHotkeys.value)
  }

  nameOf = (id: AppHotkeyId) =>
    this.appHotkeyList.value.find((item) => item.appHotkey.id === id)?.appHotkey
      .meta?.name

  // One recorder for every row. `maxSteps: Infinity` records a chord or a
  // sequence: press each chord, then Enter. Escape cancels. Backspace with
  // nothing recorded clears the hotkey. App hotkeys don't fire while it
  // records. The callbacks read `this.editing` when they run.
  recorder = useHotkeyRecorder(this, {
    maxSteps: Infinity,
    // Rejecting keeps the recording open with its steps.
    validate: (hotkey, context) => {
      if (!this.editing) return false
      // Pass `context` so a hotkey spelled differently that the same key
      // press fires counts as a conflict.
      const conflicts = this.customHotkeys.findConflicts(
        this.editing,
        hotkey,
        context,
      )
      return (
        conflicts.length === 0 ||
        `Not changed: used by ${conflicts[0]?.meta?.name}`
      )
    },
    onReject: (rejection) =>
      (this.message = rejection.message ?? 'Not changed: try another hotkey'),
    onRecord: (hotkey, context) => {
      if (!this.editing) return
      this.customHotkeys.setCustomHotkey(this.editing, hotkey, context)
      this.message = `Changed ${this.nameOf(this.editing)}`
      this.editing = null
    },
    onClear: () => {
      if (!this.editing) return
      this.customHotkeys.setCustomHotkey(this.editing, null)
      this.message = `Unassigned ${this.nameOf(this.editing)}`
      this.editing = null
    },
    onCancel: () => {
      this.message = 'Recording cancelled'
      this.editing = null
    },
  })

  change = (appHotkey: RegisteredAppHotkeyListItem['appHotkey']) => {
    this.editing = appHotkey.id
    this.message = `Recording ${appHotkey.meta?.name}: press keys, then Enter`
    this.recorder.startRecording()
  }
  reset = (appHotkey: RegisteredAppHotkeyListItem['appHotkey']) => {
    this.customHotkeys.resetCustomHotkey(appHotkey.id)
    this.message = `Reset ${appHotkey.meta?.name}`
  }
  resetAll = () => {
    this.customHotkeys.resetCustomHotkeys()
    this.message = 'Reset all hotkeys'
  }

  <template>
    {{! Registers handlers by id. Each getter reads the id's current hotkey. }}
    {{useHotkey this.saveHotkey this.save}}
    {{useHotkey this.inboxHotkey this.goToInbox}}
    {{! Registers nothing while Archive has no hotkey. Once the user assigns
        one below, this starts firing without any change here. }}
    {{useHotkey this.archiveHotkey this.archive}}
    {{! The default `ignoreInputs: 'auto'` lets Mod shortcuts fire in text
        fields, so Mod+Enter works while typing in the note. The hotkey calls
        `preventDefault`, so the textarea gets no new line. `meta` is merged
        over the declared meta for this registration only: registration lists,
        such as the buttons below, show "Publish note"; the cheat sheet keeps
        the declared "Publish". }}
    {{useHotkey
      this.publishHotkey
      this.publish
      enabled=this.hasNote
      meta=(hash name='Publish note')
    }}

    <div class='app'>
      <header>
        <h1>App Hotkeys</h1>
        <p>
          Declare every hotkey once with <code>defineAppHotkeys</code>, register
          handlers by id, list them in a cheat sheet, and let users change them.
        </p>
      </header>

      <main>
        <section class='demo-section'>
          <h2>Register app hotkeys</h2>
          <p>
            Components register a handler for an app hotkey by its id. The
            labels follow the hotkeys you change below.
          </p>
          <ul>
            <li>Save: <kbd>{{this.label this.saveHotkey.hotkey}}</kbd></li>
            <li>Go to inbox: <kbd>{{this.label this.inboxHotkey.hotkey}}</kbd></li>
            <li>Archive: <kbd>{{this.label this.archiveHotkey.hotkey}}</kbd></li>
          </ul>
          <p role='status'>{{if
              this.lastAction
              (concat 'Last action: ' this.lastAction)
              'No action yet'
            }}</p>
        </section>

        <section class='demo-section'>
          <h2>Enabled getter and call-site meta</h2>
          <p>
            Type a note, then press
            <kbd>{{this.label this.publishHotkey.hotkey}}</kbd>. Publish does
            nothing while the note is empty.
          </p>
          <label>
            Note
            <textarea id='note' rows='3'></textarea>
          </label>
          <p role='status'>{{this.publishedText}}</p>
        </section>

        <section class='demo-section'>
          <h2>Run actions without a key press</h2>
          <p>
            Each button calls the registration's <code>trigger()</code>, which
            runs its handler and returns whether it ran. It checks only
            <code>enabled</code>.
          </p>
          <div class='toolbar'>
            {{#each this.appHotkeyRegistrations key='id' as |reg|}}
              <button type='button' {{on 'click' (fn this.run reg)}}>
                {{reg.options.meta.name}}
              </button>
            {{/each}}
          </div>
          <p role='status'>{{or this.toolbarResult 'No button clicked'}}</p>
        </section>

        <section class='demo-section'>
          <h2>Cheat sheet</h2>
          <p>
            Lists every app hotkey, including ones no mounted component
            registers, such as Archive before it has a hotkey.
          </p>
          {{#each this.groups as |group|}}
            <div>
              <h3>{{group.group}}</h3>
              <ul>
                {{#each group.items as |item|}}
                  <li>
                    {{item.appHotkey.meta.name}}:
                    <kbd>{{this.label item.appHotkey.hotkey}}</kbd>{{if
                      item.isCustom
                      ' (custom)'
                    }}
                    <br />
                    <small>{{item.appHotkey.meta.description}}</small>
                  </li>
                {{/each}}
              </ul>
            </div>
          {{/each}}
          <p role='status'>{{this.customizedText}}</p>
        </section>

        <section class='demo-section'>
          <h2>Change hotkeys</h2>
          <p>
            Changes are saved to <code>localStorage</code> and survive a reload.
            Only differences from the declared defaults are saved, so users who
            never changed a hotkey get your new defaults.
          </p>
          <table>
            <tbody>
              {{#each this.appHotkeyList.value as |item|}}
                <tr>
                  <th scope='row'>{{item.appHotkey.meta.name}}</th>
                  <td>
                    <kbd>{{#if (eq this.editing item.appHotkey.id)}}{{or
                          (this.formatForDisplay this.recorder.steps)
                          'Press keys'
                        }}{{else}}{{this.label item.appHotkey.hotkey}}{{/if}}</kbd>
                  </td>
                  <td>
                    <button
                      type='button'
                      disabled={{this.recorder.isRecording}}
                      {{on 'click' (fn this.change item.appHotkey)}}
                    >Change</button>
                    <button
                      type='button'
                      disabled={{or this.recorder.isRecording (not item.isCustom)}}
                      {{on 'click' (fn this.reset item.appHotkey)}}
                    >Reset</button>
                  </td>
                </tr>
              {{/each}}
            </tbody>
          </table>
          <p>Saved: <code>{{this.saved}}</code></p>
          <button
            type='button'
            disabled={{this.recorder.isRecording}}
            {{on 'click' this.resetAll}}
          >Reset all</button>
          <p role='status'>{{this.message}}</p>
        </section>
      </main>
    </div>
  </template>
}
export default App