Skip to content

Solid Example: CreateHeldKeys

/* @refresh reload */

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

function App() {
  const formatForDisplay = createFormatForDisplay()
  // Held keys in press order, such as ['Shift', 'A']. Updates on every
  // keydown and keyup, and empties when the window loses focus.
  const heldKeys = createHeldKeys()
  // Each held key's physical `event.code`, such as { Shift: 'ShiftLeft' }.
  const heldCodes = createHeldKeyCodes()

  const [history, setHistory] = createSignal<Array<string>>([])
  const [lastAction, setLastAction] = createSignal('none')
  const [boldEnabled, setBoldEnabled] = createSignal(true)

  // Once every key is released, records the most keys held at once, such as
  // 'Shift + Control + A', and keeps the last 10.
  let mostHeld: Array<string> = []
  createEffect(heldKeys, (keys) => {
    if (keys.length > mostHeld.length) mostHeld = keys
    if (keys.length > 0 || mostHeld.length === 0) return
    const combination = mostHeld.join(' + ')
    mostHeld = []
    setHistory((h) => [...h.slice(-9), combination])
  })

  // Mod+S would open the browser's Save dialog. A matched hotkey calls
  // `preventDefault` by default, so the page handles it instead.
  createHotkey('Mod+S', () => setLastAction('Save'))
  // While `enabled` is false, Mod+B doesn't fire, and its hint stays hidden.
  // The options accessor keeps `enabled` in step with the checkbox.
  createHotkey(
    'Mod+B',
    () => setLastAction('Bold'),
    () => ({ enabled: boldEnabled() }),
  )
  createHotkey('Mod+Shift+E', () => setLastAction('Export'))
  createHotkey('Mod+Shift+A', () => setLastAction('Archive'))

  // True while the user holds Mod, and the Mod+S above can fire. The hint
  // registers nothing: it reads the held keys and the registrations.
  const showSaveHint = createHotkeyHint('Mod+S')
  // False while Bold is disabled, even with Mod held, because no enabled
  // registration of Mod+B can fire.
  const showBoldHint = createHotkeyHint('Mod+B')
  // True while the user holds Mod, Shift, or both. Holding a modifier the
  // hotkey doesn't use, such as Alt, hides it.
  const showExportHint = createHotkeyHint('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.
  const showArchiveHint = createHotkeyHint('Mod+Shift+A', { exact: true })

  const shownHints = () =>
    [
      showSaveHint() && 'Save',
      showBoldHint() && 'Bold',
      showExportHint() && 'Export',
      showArchiveHint() && 'Archive',
    ].filter(Boolean)

  return (
    <div class="app">
      <header>
        <h1>createHeldKeys</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>
          <div class="key-display" aria-hidden="true">
            <For each={heldKeys()}>
              {(key) => (
                // `{ key }` formats a raw `event.key` value, such as
                // 'Control' as ⌃ on macOS.
                <kbd class="large">{formatForDisplay({ key })}</kbd>
              )}
            </For>
          </div>
          <p role="status">
            {heldKeys().length > 0
              ? `Held: ${heldKeys().join(' + ')}`
              : 'No keys held'}
          </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">
            {heldKeys().length > 0
              ? heldKeys()
                  .map((key) => `${key}: ${heldCodes()[key]}`)
                  .join(', ')
              : 'No keys held'}
          </p>
        </section>

        <section class="demo-section">
          <h2>Hotkey hints</h2>
          <p>
            Hold <kbd>{formatForDisplay('Mod')}</kbd>, <kbd>Shift</kbd>, or both
            to see which shortcuts they lead to.
          </p>
          <div class="toolbar">
            <button onClick={() => setLastAction('Save')}>
              Save{' '}
              <Show when={showSaveHint()}>
                <kbd>{formatForDisplay('Mod+S')}</kbd>
              </Show>
            </button>
            <button onClick={() => setLastAction('Bold')}>
              Bold{' '}
              <Show when={showBoldHint()}>
                <kbd>{formatForDisplay('Mod+B')}</kbd>
              </Show>
            </button>
            <button onClick={() => setLastAction('Export')}>
              Export{' '}
              <Show when={showExportHint()}>
                <kbd>{formatForDisplay('Mod+Shift+E')}</kbd>
              </Show>
            </button>
            <button onClick={() => setLastAction('Archive')}>
              Archive{' '}
              <Show when={showArchiveHint()}>
                <kbd>{formatForDisplay('Mod+Shift+A')}</kbd>
              </Show>
            </button>
          </div>
          <label>
            <input
              type="checkbox"
              checked={boldEnabled()}
              onChange={(e) => setBoldEnabled(e.currentTarget.checked)}
            />{' '}
            Enable Bold
          </label>
          <p>Last action: {lastAction()}</p>
          <p role="status">
            {shownHints().length > 0
              ? `Hints shown: ${shownHints().join(', ')}`
              : 'Hints shown: none'}
          </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">
            Recorded {history().length}{' '}
            {history().length === 1 ? 'combination' : 'combinations'}
          </p>
          <ol class="history-list">
            <For each={history()}>
              {(combination) => <li>{combination}</li>}
            </For>
          </ol>
          <button onClick={() => setHistory([])}>Clear history</button>
        </section>
      </main>

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

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