Skip to content

Svelte Example: Create Hotkeys Sequences

<script lang="ts">
  import {
    createHotkeys,
    defineHotkey,
    getFormatForDisplay,
    getHotkeyRegistrations,
  } from '@tanstack/svelte-hotkeys'

  const formatForDisplay = getFormatForDisplay()
  let lastCommand = $state('none')
  let vimEnabled = $state(true)
  let arrows = $state({ konami: 0, side: 0, steps: 0 })

  // Arrays are sequences, and chords can share the list. The second argument
  // holds options for every item: `timeout` reaches only the sequences, so
  // the Shift+G chord ignores it. Passed as a function, the shared options
  // update when `vimEnabled` changes. A sequence of letters counts as a
  // character-key shortcut, so the checkbox gives users a way to turn the
  // list off.
  createHotkeys(
    [
      {
        hotkey: ['G', 'G'],
        callback: () => (lastCommand = 'Go to top'),
        options: { meta: { name: 'Go to top' } },
      },
      {
        hotkey: 'Shift+G',
        callback: () => (lastCommand = 'Go to bottom'),
        options: { meta: { name: 'Go to bottom' } },
      },
      {
        hotkey: ['D', 'D'],
        callback: () => (lastCommand = 'Delete line'),
        options: { meta: { name: 'Delete line' } },
      },
      {
        hotkey: ['D', 'W'],
        callback: () => (lastCommand = 'Delete word'),
        options: { meta: { name: 'Delete word' } },
      },
      {
        hotkey: ['C', 'I', 'W'],
        callback: () => (lastCommand = 'Change inner word'),
        options: { meta: { name: 'Change inner word' } },
      },
    ],
    () => ({ timeout: 1500, enabled: vimEnabled }),
  )

  // createHotkeys gives every array item one type that fits any hotkey, so an
  // item's callback `context` can be a chord or a sequence. defineHotkey types
  // one definition by its hotkey and returns it unchanged. This hotkey is a
  // sequence, so `context.parsedSequence` needs no kind check, and
  // `requireReset` would be a type error because it applies only to chords.
  const konami = defineHotkey({
    hotkey: ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown'],
    callback: (_event, context) => {
      arrows.konami++
      arrows.steps = context.parsedSequence.length
    },
    // Allow 2 seconds between steps instead of the default 1 second.
    options: { timeout: 2000, meta: { name: 'Konami code' } },
  })

  // A defined hotkey and an inline item can share one array.
  createHotkeys([
    konami,
    {
      hotkey: ['ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight'],
      callback: () => arrows.side++,
      options: { meta: { name: 'Side to side' } },
    },
  ])

  // Every registration on the page. Sequence views also carry
  // matchedStepCount, the steps pressed so far in the current attempt.
  const registrations = getHotkeyRegistrations()
</script>

<div class="app">
  <header>
    <h1>Sequences with createHotkeys</h1>
    <p>
      Register several sequences, such as Vim commands, in one createHotkeys
      call. Each key must follow the previous one within the timeout.
    </p>
  </header>

  <main>
    <section class="demo-section">
      <h2>Vim-style commands</h2>
      <label>
        <input type="checkbox" bind:checked={vimEnabled} />
        Enable Vim commands
      </label>
      <p>
        Press <kbd>{formatForDisplay(['G', 'G'])}</kbd>,
        <kbd>{formatForDisplay('Shift+G')}</kbd>,
        <kbd>{formatForDisplay(['D', 'D'])}</kbd>,
        <kbd>{formatForDisplay(['D', 'W'])}</kbd>, or
        <kbd>{formatForDisplay(['C', 'I', 'W'])}</kbd>, with up to 1.5 seconds
        between keys.
      </p>
      <p role="status">Last command: {lastCommand}</p>
    </section>

    <section class="demo-section">
      <h2>Check one definition with defineHotkey</h2>
      <p>
        Press
        <kbd>
          {formatForDisplay(['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown'])}
        </kbd>
        or
        <kbd>
          {formatForDisplay([
            'ArrowLeft',
            'ArrowRight',
            'ArrowLeft',
            'ArrowRight',
          ])}
        </kbd>.
      </p>
      <p role="status">
        Konami code: {arrows.konami}{arrows.steps > 0
          ? ` (${arrows.steps} steps)`
          : ''}, Side to side: {arrows.side}
      </p>
    </section>

    <section class="demo-section">
      <h2>List the registrations</h2>
      <p role="status">{registrations.hotkeys.length} hotkeys registered</p>
      <table class="registrations-table">
        <thead>
          <tr>
            <th>Hotkey</th>
            <th>Name</th>
            <th>Progress</th>
            <th>Fired</th>
          </tr>
        </thead>
        <tbody>
          {#each registrations.hotkeys as reg (reg.id)}
            <tr>
              <td><kbd>{formatForDisplay(reg.hotkey)}</kbd></td>
              <td>{reg.options.meta?.name}</td>
              <td>
                {reg.kind === 'sequence'
                  ? `${reg.matchedStepCount} of ${reg.hotkey.length}`
                  : 'chord'}
              </td>
              <td>{reg.triggerCount}</td>
            </tr>
          {/each}
        </tbody>
      </table>
    </section>
  </main>
</div>