Skip to content

Svelte Example: Get Held Keys

<script lang="ts">
  import {
    createHotkey,
    getFormatForDisplay,
    getHeldKeyCodesMap,
    getHeldKeys,
    getHotkeyHint,
  } from '@tanstack/svelte-hotkeys'

  const formatForDisplay = getFormatForDisplay()
  // `keys` lists the held keys in press order, such as ['Shift', 'A']. It
  // updates on every keydown and keyup, and empties when the window loses
  // focus.
  const heldKeys = getHeldKeys()
  // `codes` maps each held key to its physical `event.code`, such as
  // { Shift: 'ShiftLeft' }.
  const heldCodes = getHeldKeyCodesMap()

  let history = $state<Array<string>>([])
  let lastAction = $state('none')
  let boldEnabled = $state(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> = []
  $effect(() => {
    const keys = heldKeys.keys
    if (keys.length > mostHeld.length) mostHeld = keys
    if (keys.length > 0 || mostHeld.length === 0) return
    const combination = mostHeld.join(' + ')
    mostHeld = []
    history = [...history.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', () => (lastAction = 'Save'))
  // While `enabled` is false, Mod+B doesn't fire, and its hint stays hidden.
  // The getter keeps the option in step with the checkbox.
  createHotkey(
    'Mod+B',
    () => (lastAction = 'Bold'),
    () => ({ enabled: boldEnabled }),
  )
  createHotkey('Mod+Shift+E', () => (lastAction = 'Export'))
  createHotkey('Mod+Shift+A', () => (lastAction = 'Archive'))

  // `visible` is 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 saveHint = getHotkeyHint('Mod+S')
  // False while Bold is disabled, even with Mod held, because no enabled
  // registration of Mod+B can fire.
  const boldHint = getHotkeyHint('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 exportHint = getHotkeyHint('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 archiveHint = getHotkeyHint('Mod+Shift+A', { exact: true })

  const shownHints = $derived(
    [
      saveHint.visible && 'Save',
      boldHint.visible && 'Bold',
      exportHint.visible && 'Export',
      archiveHint.visible && 'Archive',
    ].filter(Boolean),
  )
</script>

<div class="app">
  <header>
    <h1>getHeldKeys</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">
        <!-- `{ key }` formats a raw `event.key` value, such as 'Control' as ⌃
             on macOS. -->
        {#each heldKeys.keys as key (key)}
          <kbd class="large">{formatForDisplay({ key })}</kbd>
        {/each}
      </div>
      <p role="status">
        {heldKeys.keys.length > 0
          ? `Held: ${heldKeys.keys.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.keys.length > 0
          ? heldKeys.keys
              .map((key) => `${key}: ${heldCodes.codes[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={() => (lastAction = 'Save')}>
          Save {#if saveHint.visible}<kbd>{formatForDisplay('Mod+S')}</kbd>{/if}
        </button>
        <button onclick={() => (lastAction = 'Bold')}>
          Bold {#if boldHint.visible}<kbd>{formatForDisplay('Mod+B')}</kbd>{/if}
        </button>
        <button onclick={() => (lastAction = 'Export')}>
          Export {#if exportHint.visible}<kbd
              >{formatForDisplay('Mod+Shift+E')}</kbd
            >{/if}
        </button>
        <button onclick={() => (lastAction = 'Archive')}>
          Archive {#if archiveHint.visible}<kbd
              >{formatForDisplay('Mod+Shift+A')}</kbd
            >{/if}
        </button>
      </div>
      <label>
        <input type="checkbox" bind:checked={boldEnabled} />
        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">
        {#each history as combination, i (i)}
          <li>{combination}</li>
        {/each}
      </ol>
      <button onclick={() => (history = [])}>Clear history</button>
    </section>
  </main>
</div>