TanStack

Solid Example: App Hotkeys

/* @refresh reload */

import { render } from '@solidjs/web'
import { TanStackDevtools } from '@tanstack/solid-devtools'
import {
  HotkeysProvider,
  createAppHotkeyList,
  createFormatForDisplay,
  createHotkey,
  createHotkeyRecorder,
  createHotkeyRegistrations,
  defineAppHotkeys,
  useAppHotkeys,
  useCustomHotkeys,
} from '@tanstack/solid-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/solid-hotkeys-devtools'
import { For, Show, createSignal } from 'solid-js'
import type { AppHotkeyId } from '@tanstack/solid-hotkeys'
import './index.css'

// 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/solid-hotkeys' {
  interface Register {
    appHotkeys: typeof appHotkeys
  }
}

/** Registers handlers by id. The provider supplies each id's current hotkey. */
function Actions() {
  // An accessor, so read it inside an accessor to follow the user's changes.
  const appHotkeys = useAppHotkeys()
  const formatForDisplay = createFormatForDisplay()
  const [lastAction, setLastAction] = createSignal('')

  createHotkey(
    () => appHotkeys()['doc.save'],
    () => setLastAction('Save'),
  )
  createHotkey(
    () => appHotkeys()['nav.inbox'],
    () => setLastAction('Go to inbox'),
  )
  // Registers nothing while Archive has no hotkey. Once the user assigns
  // one below, this starts firing without any change here.
  createHotkey(
    () => appHotkeys()['doc.archive'],
    () => setLastAction('Archive'),
  )

  return (
    <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>
            {/* `Show` skips `null`, which `formatForDisplay` doesn't accept.
                A platform map without a hotkey for this platform formats as
                '', so that shows "Unassigned" too. */}
            <Show when={appHotkeys()['doc.save'].hotkey} fallback="Unassigned">
              {(hotkey) => <>{formatForDisplay(hotkey()) || 'Unassigned'}</>}
            </Show>
          </kbd>
        </li>
        <li>
          Go to inbox:{' '}
          <kbd>
            <Show when={appHotkeys()['nav.inbox'].hotkey} fallback="Unassigned">
              {(hotkey) => <>{formatForDisplay(hotkey()) || 'Unassigned'}</>}
            </Show>
          </kbd>
        </li>
        <li>
          Archive:{' '}
          <kbd>
            <Show
              when={appHotkeys()['doc.archive'].hotkey}
              fallback="Unassigned"
            >
              {(hotkey) => <>{formatForDisplay(hotkey()) || 'Unassigned'}</>}
            </Show>
          </kbd>
        </li>
      </ul>
      <p role="status">
        {lastAction() ? `Last action: ${lastAction()}` : 'No action yet'}
      </p>
    </section>
  )
}

/** An `enabled` getter, and `meta` added for this registration only. */
function Publisher() {
  const appHotkeys = useAppHotkeys()
  const formatForDisplay = createFormatForDisplay()
  let note!: HTMLTextAreaElement
  const [published, setPublished] = createSignal('')

  // 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.
  createHotkey(
    () => appHotkeys()['doc.publish'],
    () => setPublished(note.value.trim()),
    {
      // A getter is read on each key press and on `trigger()`. The note is
      // uncontrolled, so a plain boolean would need a signal updated on every
      // keystroke to stay current.
      enabled: () => !!note.value.trim(),
      // 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".
      meta: { name: 'Publish note' },
    },
  )

  return (
    <section class="demo-section">
      <h2>Enabled getter and call-site meta</h2>
      <p>
        Type a note, then press{' '}
        <kbd>
          <Show when={appHotkeys()['doc.publish'].hotkey} fallback="Unassigned">
            {(hotkey) => <>{formatForDisplay(hotkey()) || 'Unassigned'}</>}
          </Show>
        </kbd>
        . Publish does nothing while the note is empty.
      </p>
      <label>
        Note
        <textarea ref={note} rows={3} />
      </label>
      <p role="status">
        {published() ? `Published: ${published()}` : 'Nothing published'}
      </p>
    </section>
  )
}

/** Runs registered app hotkeys from buttons, without a key press. */
function Toolbar() {
  const [result, setResult] = createSignal('')
  // Every mounted registration. A registration's meta includes call-site
  // meta, so Publish shows as "Publish note".
  const registrations = createHotkeyRegistrations()

  return (
    <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">
        {/* Only registrations of app hotkeys. */}
        <For
          each={registrations().filter(
            (reg) => reg.options.appHotkeyId !== undefined,
          )}
        >
          {(reg) => (
            <button
              type="button"
              onClick={() => {
                const name = reg.options.meta?.name
                setResult(reg.trigger() ? `Ran: ${name}` : `Not run: ${name}`)
              }}
            >
              {reg.options.meta?.name}
            </button>
          )}
        </For>
      </div>
      <p role="status">{result() || 'No button clicked'}</p>
    </section>
  )
}

/** Lists every app hotkey, mounted or not, grouped by `meta.group`. */
function CheatSheet() {
  const formatForDisplay = createFormatForDisplay()
  const items = createAppHotkeyList()
  const groups = () => [
    ...new Set(items().map((item) => item.appHotkey.meta?.group)),
  ]
  const customCount = () => items().filter((item) => item.isCustom).length

  return (
    <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>
      <For each={groups()}>
        {(group) => (
          <div>
            <h3>{group}</h3>
            <ul>
              <For
                each={items().filter(
                  (item) => item.appHotkey.meta?.group === group,
                )}
              >
                {(item) => (
                  <li>
                    {item.appHotkey.meta?.name}:{' '}
                    <kbd>
                      {(item.appHotkey.hotkey &&
                        formatForDisplay(item.appHotkey.hotkey)) ||
                        'Unassigned'}
                    </kbd>
                    {item.isCustom && ' (custom)'}
                    <br />
                    <small>{item.appHotkey.meta?.description}</small>
                  </li>
                )}
              </For>
            </ul>
          </div>
        )}
      </For>
      <p role="status">
        Customized: {customCount()} of {items().length}
      </p>
    </section>
  )
}

/** Rebinds app hotkeys. The provider saves each change. */
function Settings() {
  const formatForDisplay = createFormatForDisplay()
  const items = createAppHotkeyList()
  const {
    customHotkeys,
    setCustomHotkey,
    resetCustomHotkey,
    resetCustomHotkeys,
    findConflicts,
  } = useCustomHotkeys()
  // The row being recorded. The recorder callbacks below read it when a key
  // is pressed, so they always see the current row.
  const [editing, setEditing] = createSignal<AppHotkeyId | null>(null)
  const [message, setMessage] = createSignal('No changes')

  const nameOf = (id: AppHotkeyId) =>
    items().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.
  const recorder = createHotkeyRecorder({
    maxSteps: Infinity,
    // Rejecting keeps the recording open with its steps.
    validate: (hotkey, context) => {
      const id = editing()
      if (!id) return false
      // Pass `context` so a hotkey spelled differently that the same key
      // press fires counts as a conflict.
      const conflicts = findConflicts(id, hotkey, context)
      return (
        conflicts.length === 0 ||
        `Not changed: used by ${conflicts[0]?.meta?.name}`
      )
    },
    onReject: (rejection) =>
      setMessage(rejection.message ?? 'Not changed: try another hotkey'),
    onRecord: (hotkey, context) => {
      const id = editing()
      if (!id) return
      setCustomHotkey(id, hotkey, context)
      setMessage(`Changed ${nameOf(id)}`)
      setEditing(null)
    },
    onClear: () => {
      const id = editing()
      if (!id) return
      setCustomHotkey(id, null)
      setMessage(`Unassigned ${nameOf(id)}`)
      setEditing(null)
    },
    onCancel: () => {
      setMessage('Recording cancelled')
      setEditing(null)
    },
  })

  return (
    <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>
          <For each={items()}>
            {(item) => (
              <tr>
                <th scope="row">{item.appHotkey.meta?.name}</th>
                <td>
                  <kbd>
                    {editing() === item.appHotkey.id
                      ? formatForDisplay(recorder.steps()) || 'Press keys'
                      : (item.appHotkey.hotkey &&
                          formatForDisplay(item.appHotkey.hotkey)) ||
                        'Unassigned'}
                  </kbd>
                </td>
                <td>
                  <button
                    type="button"
                    disabled={recorder.isRecording()}
                    onClick={() => {
                      setEditing(item.appHotkey.id)
                      setMessage(
                        `Recording ${item.appHotkey.meta?.name}: press keys, then Enter`,
                      )
                      recorder.startRecording()
                    }}
                  >
                    Change
                  </button>{' '}
                  <button
                    type="button"
                    disabled={recorder.isRecording() || !item.isCustom}
                    onClick={() => {
                      resetCustomHotkey(item.appHotkey.id)
                      setMessage(`Reset ${item.appHotkey.meta?.name}`)
                    }}
                  >
                    Reset
                  </button>
                </td>
              </tr>
            )}
          </For>
        </tbody>
      </table>
      <p>
        Saved: <code>{JSON.stringify(customHotkeys())}</code>
      </p>
      <button
        type="button"
        disabled={recorder.isRecording()}
        onClick={() => {
          resetCustomHotkeys()
          setMessage('Reset all hotkeys')
        }}
      >
        Reset all
      </button>
      <p role="status">{message()}</p>
    </section>
  )
}

function App() {
  return (
    <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>
        <Actions />
        <Publisher />
        <Toolbar />
        <CheatSheet />
        <Settings />
      </main>

      <TanStackDevtools plugins={[hotkeysDevtoolsPlugin()]} />
    </div>
  )
}

const root = document.getElementById('root')!
render(
  // `customHotkeys` is the user's saved changes, read when the provider is
  // created. `onCustomHotkeysChange` gets every change, ready to save. Your
  // app owns storage, so swap localStorage for a server without other changes.
  () => (
    <HotkeysProvider
      appHotkeys={appHotkeys}
      customHotkeys={JSON.parse(
        localStorage.getItem('tanstack-hotkeys-app-hotkeys') ?? '{}',
      )}
      onCustomHotkeysChange={(customHotkeys) =>
        localStorage.setItem(
          'tanstack-hotkeys-app-hotkeys',
          JSON.stringify(customHotkeys),
        )
      }
    >
      <App />
    </HotkeysProvider>
  ),
  root,
)