Skip to content

Solid Example: CreateHotkey

/* @refresh reload */

import { render } from '@solidjs/web'
import { TanStackDevtools } from '@tanstack/solid-devtools'
import {
  HotkeysProvider,
  createFormatForDisplay,
  createHotkey,
} from '@tanstack/solid-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/solid-hotkeys-devtools'
import { Show, createSignal } from 'solid-js'
import './index.css'

const devtoolsPlugins = [hotkeysDevtoolsPlugin()]

function App() {
  const formatForDisplay = createFormatForDisplay()

  // Chords as strings and objects
  const [lastBasic, setLastBasic] = createSignal('none')

  // `hotkey` is the chord as registered, with `Mod` kept. `parsedChord` has
  // `Mod` resolved for this platform: Meta on macOS, Control elsewhere.
  // Mod+S would open the browser's Save dialog. A matched hotkey calls
  // `preventDefault` by default, so the dialog stays closed.
  // `meta` doesn't change matching. The devtools and cheat sheets read it.
  createHotkey(
    'Mod+S',
    (_event, { hotkey, parsedChord }) =>
      setLastBasic(
        `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
      ),
    { meta: { name: 'Save', description: 'Save the document' } },
  )

  // Function keys, arrow keys, and named keys use their `event.key` names.
  // To match a key by position instead, write its code: 'Mod+[KeyS]'.
  createHotkey('F2', (_event, { hotkey, parsedChord }) =>
    setLastBasic(
      `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
    ),
  )
  createHotkey('Alt+ArrowUp', (_event, { hotkey, parsedChord }) =>
    setLastBasic(
      `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
    ),
  )
  createHotkey('Escape', (_event, { hotkey, parsedChord }) =>
    setLastBasic(
      `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
    ),
  )

  // The same chord as an object, for chords built from data such as
  // modifier checkboxes. `hotkey` reports it as the string 'Mod+Shift+S'.
  createHotkey(
    { key: 'S', mod: true, shift: true },
    (_event, { hotkey, parsedChord }) =>
      setLastBasic(
        `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`,
      ),
  )

  // Fire once while held
  const [resetCount, setResetCount] = createSignal(0)

  // Chords only. Without `requireReset`, holding Mod+K fires again on every
  // key repeat. With it, Mod+K fires once until you release a key.
  createHotkey('Mod+K', () => setResetCount((count) => count + 1), {
    requireReset: true,
  })

  // Fire on key release
  const [previewShown, setPreviewShown] = createSignal(false)

  // Hold Mod+P to show the preview. The keydown hotkey shows it, and the
  // keyup hotkey hides it when you release P or Mod. The two don't conflict
  // because their `eventType` differs. A keyup hotkey still calls
  // `preventDefault` on the keydown, so the print dialog doesn't open.
  createHotkey('Mod+P', () => setPreviewShown(true))
  createHotkey('Mod+P', () => setPreviewShown(false), { eventType: 'keyup' })

  // Turn hotkeys on and off
  const [stateEnabled, setStateEnabled] = createSignal(true)
  const [enabledCounts, setEnabledCounts] = createSignal({ e: 0, g: 0 })
  let getterCheckbox: HTMLInputElement | undefined

  // A disabled hotkey stays registered and visible in the devtools. It
  // doesn't call `preventDefault`, so the browser handles Mod+E. Options
  // passed as an accessor re-run when a signal they read changes, and the
  // registration updates in place.
  createHotkey(
    'Mod+E',
    () => setEnabledCounts((counts) => ({ ...counts, e: counts.e + 1 })),
    () => ({ enabled: stateEnabled() }),
  )

  // A function is read on each key press, for state that lives outside
  // signals. This one reads an uncontrolled checkbox. Keep the function
  // cheap: it runs on every key press.
  createHotkey(
    'Mod+G',
    () => setEnabledCounts((counts) => ({ ...counts, g: counts.g + 1 })),
    { enabled: () => getterCheckbox?.checked ?? false },
  )

  // Listen on one element
  const [targetCounts, setTargetCounts] = createSignal({ panel: 0, drawer: 0 })
  const [panel, setPanel] = createSignal<HTMLDivElement | null>(null)
  const [drawerOpen, setDrawerOpen] = createSignal(false)
  // The ref sets the signal when the drawer mounts. Solid doesn't reset a
  // ref on unmount, so the options below also check `drawerOpen`.
  const [drawer, setDrawer] = createSignal<HTMLDivElement | null>(null)

  // An element only gets key events while it or something inside it has
  // focus, so the panel has `tabindex={0}`. Enter does nothing elsewhere.
  // Keep the element in a signal and pass the options as an accessor, so
  // the hotkey attaches once the element exists.
  createHotkey(
    'Enter',
    () => setTargetCounts((counts) => ({ ...counts, panel: counts.panel + 1 })),
    () => ({ target: panel() }),
  )

  // While the target is null, nothing is registered. Each target gets its own
  // Enter, so these two don't conflict.
  createHotkey(
    'Enter',
    () =>
      setTargetCounts((counts) => ({ ...counts, drawer: counts.drawer + 1 })),
    () => ({ target: drawerOpen() ? drawer() : null }),
  )

  // Typing in text fields
  const [lastInputs, setLastInputs] = createSignal('none')

  // The default `ignoreInputs: 'auto'` decides from the hotkey. A key that
  // types or edits text, such as N, Shift+N, Alt+N, or an arrow key, is
  // skipped while a text field has focus, so N types into the field.
  createHotkey('N', (_event, { hotkey }) => setLastInputs(hotkey))

  // With 'auto', Control and Meta chords, Escape, and function keys fire in
  // text fields too, because they type nothing.
  createHotkey('Mod+Enter', (_event, { hotkey }) => setLastInputs(hotkey))

  // `true` skips text fields for every hotkey. Mod+A then selects the field's
  // text, and selects nothing on the rest of the page.
  createHotkey('Mod+A', (_event, { hotkey }) => setLastInputs(hotkey), {
    ignoreInputs: true,
  })

  // `false` fires in text fields too. 'auto' would skip Shift+Enter there.
  createHotkey('Shift+Enter', (_event, { hotkey }) => setLastInputs(hotkey), {
    ignoreInputs: false,
  })

  // The browser's default action
  const [lastPrevent, setLastPrevent] = createSignal('none')
  const [preventInput, setPreventInput] = createSignal<HTMLInputElement | null>(
    null,
  )

  // These hotkeys listen on the text field. A hotkey targeted at a field
  // always gets its keys, whatever `ignoreInputs` says. By default a matched
  // hotkey calls `preventDefault`, so 1 doesn't type.
  createHotkey(
    '1',
    (_event, { hotkey }) => setLastPrevent(hotkey),
    () => ({ target: preventInput() }),
  )

  // `false` lets the browser act too, so 2 fires the hotkey and types.
  createHotkey(
    '2',
    (_event, { hotkey }) => setLastPrevent(hotkey),
    () => ({ target: preventInput(), preventDefault: false }),
  )

  // A disabled hotkey normally leaves the key to the browser. `'always'`
  // keeps calling `preventDefault` while the hotkey is disabled, so 3 doesn't
  // type and the callback doesn't run.
  createHotkey(
    '3',
    (_event, { hotkey }) => setLastPrevent(hotkey),
    () => ({
      target: preventInput(),
      enabled: false,
      preventDefault: 'always',
    }),
  )

  // Stop outer hotkeys
  const [stopPanel, setStopPanel] = createSignal(true)
  const [stopCounts, setStopCounts] = createSignal({ panel: 0, page: 0 })
  const [stopPanelElement, setStopPanelElement] =
    createSignal<HTMLDivElement | null>(null)

  // With focus inside the panel, its hotkey runs before the page's hotkey
  // for the same key. `stopPropagation: true`, the default, stops the event
  // there, so the page's Mod+D doesn't fire. With `false`, both fire.
  createHotkey(
    'Mod+D',
    () => setStopCounts((counts) => ({ ...counts, panel: counts.panel + 1 })),
    () => ({ target: stopPanelElement(), stopPropagation: stopPanel() }),
  )
  createHotkey('Mod+D', () =>
    setStopCounts((counts) => ({ ...counts, page: counts.page + 1 })),
  )

  // Run before a widget's own handler
  const [captureCounts, setCaptureCounts] = createSignal({
    bubble: 0,
    capture: 0,
  })

  // Hotkeys listen in the bubble phase, after the focused element's own
  // handlers. The widget below calls `stopPropagation` on every key, so
  // Mod+ArrowUp never reaches the page while the widget has focus.
  createHotkey('Mod+ArrowUp', () =>
    setCaptureCounts((counts) => ({ ...counts, bubble: counts.bubble + 1 })),
  )

  // `capture: true` runs the hotkey on the way down, before the widget's
  // handler. With the default `stopPropagation: true`, the widget then
  // doesn't see Mod+ArrowDown at all.
  createHotkey(
    'Mod+ArrowDown',
    () =>
      setCaptureCounts((counts) => ({
        ...counts,
        capture: counts.capture + 1,
      })),
    { capture: true },
  )

  // Keys another listener already handled
  const [handledCounts, setHandledCounts] = createSignal({ b: 0, i: 0 })

  // The editor below calls `preventDefault` on its Control and Meta chords,
  // as rich text editors do for Mod+B. With `ignoreDefaultPrevented: true`,
  // the hotkey skips a key press that another listener already prevented.
  createHotkey(
    'Mod+B',
    () => setHandledCounts((counts) => ({ ...counts, b: counts.b + 1 })),
    { ignoreDefaultPrevented: true },
  )

  // By default a hotkey fires even when the key was already prevented.
  createHotkey('Mod+I', () =>
    setHandledCounts((counts) => ({ ...counts, i: counts.i + 1 })),
  )

  // Duplicate hotkeys
  const [duplicateCounts, setDuplicateCounts] = createSignal({ y: 0, u: 0 })

  // Two registrations of the same hotkey on the same target both run.
  // `conflictBehavior` is checked when the second one registers, so set it
  // on each registration that may register second. 'allow' registers both
  // silently.
  createHotkey(
    'Mod+Y',
    () => setDuplicateCounts((counts) => ({ ...counts, y: counts.y + 1 })),
    { conflictBehavior: 'allow' },
  )
  createHotkey(
    'Mod+Y',
    () => setDuplicateCounts((counts) => ({ ...counts, y: counts.y + 1 })),
    { conflictBehavior: 'allow' },
  )

  // The default, 'warn', also registers both, and logs
  // "[hotkeys] 'Mod+U' is already registered" in development. This example
  // triggers that warning on purpose. 'error' throws when the second one
  // registers instead.
  createHotkey('Mod+U', () =>
    setDuplicateCounts((counts) => ({ ...counts, u: counts.u + 1 })),
  )
  createHotkey('Mod+U', () =>
    setDuplicateCounts((counts) => ({ ...counts, u: counts.u + 1 })),
  )

  return (
    <div class="app">
      <header>
        <h1>createHotkey</h1>
        <p>
          createHotkey registers one hotkey while its component is mounted. Each
          section below shows one way to write a hotkey or one of its options.
        </p>
      </header>

      <main>
        <section class="demo-section">
          <h2>Chords as strings and objects</h2>
          <p>
            Press <kbd>{formatForDisplay('Mod+S')}</kbd>,{' '}
            <kbd>{formatForDisplay('F2')}</kbd>,{' '}
            <kbd>{formatForDisplay('Alt+ArrowUp')}</kbd>,{' '}
            <kbd>{formatForDisplay('Escape')}</kbd>, or{' '}
            <kbd>{formatForDisplay('Mod+Shift+S')}</kbd>. The last one is
            written as an object.
          </p>
          <p role="status" class="info-box">
            Last fired: {lastBasic()}
          </p>
          <p class="hint">
            For a hotkey per platform or more than one hotkey per action, see
            the createHotkey-alternates example. For sequences such as G then H,
            see createHotkey-sequences.
          </p>
        </section>

        <section class="demo-section">
          <h2>Fire once while held</h2>
          <p>
            Hold <kbd>{formatForDisplay('Mod+K')}</kbd>. The count goes up once
            per press, not on every key repeat.
          </p>
          <p role="status" class="info-box">
            Mod+K: {resetCount()}
          </p>
        </section>

        <section class="demo-section">
          <h2>Fire on key release</h2>
          <p>
            Hold <kbd>{formatForDisplay('Mod+P')}</kbd> to show the preview.
            Release it to hide the preview.
          </p>
          <p role="status" class="info-box">
            {previewShown() ? 'Preview shown' : 'Preview hidden'}
          </p>
        </section>

        <section class="demo-section">
          <h2>Turn hotkeys on and off</h2>
          <p>
            <kbd>{formatForDisplay('Mod+E')}</kbd> reads <code>enabled</code>{' '}
            from a signal. <kbd>{formatForDisplay('Mod+G')}</kbd> reads it from
            a function on each key press.
          </p>
          <label class="control">
            <input
              type="checkbox"
              checked={stateEnabled()}
              onChange={(event) => setStateEnabled(event.currentTarget.checked)}
            />
            Enable Mod+E
          </label>
          <label class="control">
            <input
              type="checkbox"
              ref={(element) => (getterCheckbox = element)}
              checked
            />
            Enable Mod+G
          </label>
          <p role="status" class="info-box">
            Mod+E: {enabledCounts().e}, Mod+G: {enabledCounts().g}
          </p>
        </section>

        <section class="demo-section">
          <h2>Listen on one element</h2>
          <p>
            Click the panel or the drawer, then press{' '}
            <kbd>{formatForDisplay('Enter')}</kbd>. Each has its own hotkey.
          </p>
          <div class="target-grid">
            <div ref={setPanel} tabindex={0} class="target-area">
              Panel
            </div>
            <div>
              <button
                aria-expanded={drawerOpen() ? 'true' : 'false'}
                onClick={() => setDrawerOpen(!drawerOpen())}
              >
                Toggle drawer
              </button>
              <Show when={drawerOpen()}>
                <div ref={setDrawer} tabindex={0} class="target-area">
                  Drawer
                </div>
              </Show>
            </div>
          </div>
          <p role="status" class="info-box">
            Panel: {targetCounts().panel}, drawer: {targetCounts().drawer}
          </p>
        </section>

        <section class="demo-section">
          <h2>Typing in text fields</h2>
          <p>
            Press <kbd>{formatForDisplay('N')}</kbd>,{' '}
            <kbd>{formatForDisplay('Mod+Enter')}</kbd>,{' '}
            <kbd>{formatForDisplay('Mod+A')}</kbd>, and{' '}
            <kbd>{formatForDisplay('Shift+Enter')}</kbd> on the page, then in
            the text field. In the field, N types and Mod+A selects the text.
          </p>
          <label class="control">
            Text field <input type="text" />
          </label>
          <p role="status" class="info-box">
            Last fired: {lastInputs()}
          </p>
        </section>

        <section class="demo-section">
          <h2>The browser's default action</h2>
          <p>
            Type 1, 2, and 3 in the field. Only 2 types, because the hotkeys for
            1 and 3 call <code>preventDefault</code>. The hotkey for 3 is
            disabled, so it doesn't fire.
          </p>
          <label class="control">
            Digits <input type="text" ref={setPreventInput} />
          </label>
          <p role="status" class="info-box">
            Last fired: {lastPrevent()}
          </p>
        </section>

        <section class="demo-section">
          <h2>Stop outer hotkeys</h2>
          <p>
            The panel and the page each have a{' '}
            <kbd>{formatForDisplay('Mod+D')}</kbd> hotkey. Click the panel and
            press it, then turn off stopping and press it again.
          </p>
          <label class="control">
            <input
              type="checkbox"
              checked={stopPanel()}
              onChange={(event) => setStopPanel(event.currentTarget.checked)}
            />
            Stop propagation in the panel
          </label>
          <div ref={setStopPanelElement} tabindex={0} class="target-area">
            Panel
          </div>
          <p role="status" class="info-box">
            Panel: {stopCounts().panel}, page: {stopCounts().page}
          </p>
        </section>

        <section class="demo-section">
          <h2>Run before a widget's own handler</h2>
          <p>
            Click the widget, which stops every key from reaching the page. Then
            press <kbd>{formatForDisplay('Mod+ArrowUp')}</kbd> and{' '}
            <kbd>{formatForDisplay('Mod+ArrowDown')}</kbd>. Only the capture
            hotkey fires.
          </p>
          {/* Stands in for a component that handles keys itself. Solid
              delegates `onKeyDown` to the render root, so stopping it there
              still keeps the key from reaching `document`. */}
          <div
            tabindex={0}
            class="target-area"
            onKeyDown={(event) => event.stopPropagation()}
          >
            Widget
          </div>
          <p role="status" class="info-box">
            Bubble: {captureCounts().bubble}, capture: {captureCounts().capture}
          </p>
        </section>

        <section class="demo-section">
          <h2>Keys another listener already handled</h2>
          <p>
            Click the editor and press <kbd>{formatForDisplay('Mod+B')}</kbd>{' '}
            and <kbd>{formatForDisplay('Mod+I')}</kbd>. The editor prevents
            both, so only Mod+I fires. Outside the editor, both fire.
          </p>
          {/* Stands in for a rich text editor that handles its own chords. */}
          <div
            tabindex={0}
            class="target-area"
            onKeyDown={(event) => {
              if (event.ctrlKey || event.metaKey) event.preventDefault()
            }}
          >
            Editor
          </div>
          <p role="status" class="info-box">
            Mod+B: {handledCounts().b}, Mod+I: {handledCounts().i}
          </p>
        </section>

        <section class="demo-section">
          <h2>Duplicate hotkeys</h2>
          <p>
            <kbd>{formatForDisplay('Mod+Y')}</kbd> and{' '}
            <kbd>{formatForDisplay('Mod+U')}</kbd> are each registered twice, so
            one press runs two callbacks. Mod+U uses the default{' '}
            <code>conflictBehavior</code>, so the console shows a warning for it
            in development.
          </p>
          <p role="status" class="info-box">
            Mod+Y: {duplicateCounts().y}, Mod+U: {duplicateCounts().u}
          </p>
        </section>
      </main>

      <TanStackDevtools plugins={devtoolsPlugins} />
    </div>
  )
}

render(
  () => (
    // The provider is optional. Its `defaultOptions.hotkey` sets defaults for
    // every hotkey, and each primitive's own options override them.
    <HotkeysProvider>
      <App />
    </HotkeysProvider>
  ),
  document.getElementById('root')!,
)