Skip to content

Solid Example: CreateHotkeys

/* @refresh reload */

import { render } from '@solidjs/web'
import { TanStackDevtools } from '@tanstack/solid-devtools'
import {
  HotkeysProvider,
  createFormatForDisplay,
  createHotkeyRegistrations,
  createHotkeys,
  defineHotkey,
  findHotkeyConflicts,
  normalizeHotkey,
  validateHotkey,
} from '@tanstack/solid-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/solid-hotkeys-devtools'
import { For, createSignal } from 'solid-js'
import type { Hotkey, HotkeyIssue } from '@tanstack/solid-hotkeys'
import './index.css'

const devtoolsPlugins = [hotkeysDevtoolsPlugin()]

function App() {
  return (
    <div class="app">
      <header>
        <h1>createHotkeys</h1>
        <p>
          Register a list of hotkeys in one createHotkeys call. The list can
          change length after the component runs, which separate createHotkey
          calls can't.
        </p>
      </header>
      <main>
        <RegisterMultipleHotkeys />
        <DefineHotkeyDemo />
        <SharedOptionsDemo />
        <ListFromDataDemo />
        <RegistrationsTable />
      </main>
      <TanStackDevtools plugins={devtoolsPlugins} />
    </div>
  )
}

function RegisterMultipleHotkeys() {
  const formatForDisplay = createFormatForDisplay()
  const [counts, setCounts] = createSignal({ save: 0, undo: 0, redo: 0 })

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

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

function DefineHotkeyDemo() {
  const formatForDisplay = createFormatForDisplay()
  const [pins, setPins] = createSignal({ count: 0, modifiers: '' })

  // createHotkeys 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, as createHotkey types its arguments,
  // and returns it unchanged. Use it for a definition you keep in a variable.
  const pin = defineHotkey({
    hotkey: 'Shift+P',
    // Shift+P is a chord, so `context.parsedChord` needs no kind check.
    callback: (_event, context) =>
      setPins((p) => ({
        count: p.count + 1,
        modifiers: 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.
  createHotkeys([
    pin,
    {
      hotkey: 'Shift+O',
      callback: () => setPins({ count: 0, modifiers: '' }),
      options: { meta: { name: 'Clear pins' } },
    },
  ])

  return (
    <section class="demo-section">
      <h2>Check one definition with defineHotkey</h2>
      <p>
        Hold <kbd>{formatForDisplay('Shift+P')}</kbd> to pin once. Press{' '}
        <kbd>{formatForDisplay('Shift+O')}</kbd> to clear.
      </p>
      <p role="status">
        Pins: {pins().count}
        {pins().modifiers && `, modifiers: ${pins().modifiers}`}
      </p>
    </section>
  )
}

function SharedOptionsDemo() {
  const formatForDisplay = createFormatForDisplay()
  const [enabled, setEnabled] = createSignal(true)
  const [counts, setCounts] = createSignal({ a: 0, b: 0, c: 0 })

  // The second argument holds options for every item, and an item's own
  // options win. Pass it as an accessor so it follows the `enabled` signal.
  // Unchecking the box disables Action A and Action B. Action C sets
  // `enabled: true` itself, so it keeps firing.
  // `Alt+[KeyJ]` names the physical J key. On macOS, Option+J types ∆, so a
  // plain `Alt+J` depends on what the layout types there.
  createHotkeys(
    [
      {
        hotkey: 'Alt+[KeyJ]',
        callback: () => setCounts((c) => ({ ...c, a: c.a + 1 })),
        options: { meta: { name: 'Action A' } },
      },
      {
        hotkey: 'Alt+[KeyK]',
        callback: () => setCounts((c) => ({ ...c, b: c.b + 1 })),
        options: { meta: { name: 'Action B' } },
      },
      {
        hotkey: 'Alt+[KeyL]',
        callback: () => setCounts((c) => ({ ...c, c: c.c + 1 })),
        options: { enabled: true, meta: { name: 'Action C' } },
      },
    ],
    () => ({ enabled: enabled() }),
  )

  return (
    <section class="demo-section">
      <h2>Share options</h2>
      <label>
        <input
          type="checkbox"
          checked={enabled()}
          onChange={(e) => setEnabled(e.currentTarget.checked)}
        />{' '}
        Enable shared hotkeys
      </label>
      <div class="hotkey-grid">
        <div>
          <kbd>{formatForDisplay('Alt+[KeyJ]')}</kbd> Action A
        </div>
        <div>
          <kbd>{formatForDisplay('Alt+[KeyK]')}</kbd> Action B
        </div>
        <div>
          <kbd>{formatForDisplay('Alt+[KeyL]')}</kbd> Action C (always on)
        </div>
      </div>
      <p role="status">
        Action A: {counts().a}, Action B: {counts().b}, Action C: {counts().c}
      </p>
    </section>
  )
}

// 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

function ListFromDataDemo() {
  const formatForDisplay = createFormatForDisplay()
  const [shortcuts, setShortcuts] = createSignal<
    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 },
  ])
  const [newHotkey, setNewHotkey] = createSignal('')
  const [newName, setNewName] = createSignal('')
  const [message, setMessage] = createSignal('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. A component runs once, so a fixed set of createHotkey calls
  // can't follow a list that grows. createHotkeys takes an accessor for an
  // array of any length and updates when it changes. It matches items by
  // index, so removing one re-registers the items after it, and their counts
  // in the table below start over.
  createHotkeys(() =>
    shortcuts().map((s) => ({
      hotkey: s.hotkey,
      callback: () =>
        setShortcuts((prev) =>
          prev.map((item) =>
            item.id === s.id ? { ...item, count: item.count + 1 } : item,
          ),
        ),
      options: { meta: { name: s.name } },
    })),
  )

  const addShortcut = (event: SubmitEvent) => {
    event.preventDefault()
    const name = newName().trim()
    if (!name) {
      setMessage('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(newHotkey().trim())
    const issues = [...validation.errors, ...validation.warnings]
    if (issues.length > 0) {
      setMessage(issues.map(issueText).join(' '))
      return
    }
    const hotkey = normalizeHotkey(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) {
      setMessage(
        `Already used by ${conflicts[0].registration.options.meta?.name ?? 'another hotkey'}.`,
      )
      return
    }
    setShortcuts((prev) => [...prev, { id: nextId++, hotkey, name, count: 0 }])
    setMessage(`Added ${name}.`)
    setNewHotkey('')
    setNewName('')
  }

  return (
    <section class="demo-section">
      <h2>Build the list from data</h2>
      <ul class="dynamic-list">
        <For each={shortcuts()}>
          {(s) => (
            <li class="dynamic-item">
              <kbd>{formatForDisplay(s.hotkey)}</kbd>
              <span>{s.name}</span>
              <span class="count">Fired {s.count}</span>
              <button
                type="button"
                onClick={() =>
                  setShortcuts((prev) =>
                    prev.filter((item) => item.id !== s.id),
                  )
                }
              >
                Remove
              </button>
            </li>
          )}
        </For>
      </ul>
      <form class="add-form" onSubmit={addShortcut}>
        <label>
          Hotkey{' '}
          <input
            value={newHotkey()}
            placeholder="Shift+D"
            onInput={(e) => setNewHotkey(e.currentTarget.value)}
          />
        </label>
        <label>
          Name{' '}
          <input
            value={newName()}
            placeholder="Action 4"
            onInput={(e) => setNewName(e.currentTarget.value)}
          />
        </label>
        <button type="submit">Add</button>
      </form>
      <p role="status">{message()}</p>
    </section>
  )
}

function RegistrationsTable() {
  const formatForDisplay = createFormatForDisplay()
  // Every registration on the page, chords and sequences. It updates when a
  // hotkey registers, unregisters, changes `enabled`, or fires.
  const registrations = createHotkeyRegistrations()

  return (
    <section class="demo-section">
      <h2>List the registrations</h2>
      <p role="status">{registrations().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>
          <For each={registrations()}>
            {(reg) => (
              <tr>
                <td>
                  <kbd>{formatForDisplay(reg.hotkey)}</kbd>
                </td>
                <td>{reg.options.meta?.name}</td>
                <td>{reg.status}</td>
                <td>{reg.triggerCount}</td>
              </tr>
            )}
          </For>
        </tbody>
      </table>
    </section>
  )
}

render(
  () => (
    <HotkeysProvider>
      <App />
    </HotkeysProvider>
  ),
  document.getElementById('root')!,
)