Hooks

useKbd

Register keyboard shortcuts with modifier key support. Track which keys are currently pressed and log keyboard events. Works with the Kbd component for displaying shortcuts.

Basic Usage

Register shortcuts and see them trigger in real time. Try pressing the key combinations below.

+ K Search
+ S Save
+ + P Command Palette
Last action: None
<script lang="ts">
  import { Badge, Kbd } from 'sv5ui';
  import { useKbd } from 'sv5ui';

  let lastAction = $state('None');

  const { isPressed } = useKbd({
    shortcuts: {
      'ctrl+k': () => lastAction = 'Search opened',
      'ctrl+s': () => lastAction = 'Document saved',
      'ctrl+shift+p': () => lastAction = 'Command palette opened'
    }
  });
</script>

<div class="flex gap-3">
  <div class="flex items-center gap-1">
    <Kbd value="ctrl" size="sm" /> + <Kbd value="K" size="sm" />
  </div>
  <div class="flex items-center gap-1">
    <Kbd value="ctrl" size="sm" /> + <Kbd value="S" size="sm" />
  </div>
  <div class="flex items-center gap-1">
    <Kbd value="ctrl" size="sm" /> + <Kbd value="shift" size="sm" /> + <Kbd value="P" size="sm" />
  </div>
</div>

<Badge label={lastAction} variant="soft" color={lastAction === 'None' ? 'surface' : 'success'} />

Pressed Keys & Event Log

Use isPressed to check if a key is currently held down. The event log records triggered shortcuts.

Ctrl key: Released

Event Log

No events yet. Press a shortcut...

<script lang="ts">
  import { Badge, Kbd } from 'sv5ui';
  import { useKbd } from 'sv5ui';

  let eventLog = $state([]);

  const { isPressed } = useKbd({
    shortcuts: {
      'ctrl+k': () => addLog('ctrl+k'),
      'ctrl+s': () => addLog('ctrl+s')
    }
  });

  let ctrlActive = $derived(isPressed('ctrl'));

  function addLog(shortcut) {
    eventLog = [`${new Date().toLocaleTimeString()} — ${shortcut}`, ...eventLog].slice(0, 5);
  }
</script>

<Badge
  label={ctrlActive ? 'Ctrl held down' : 'Ctrl released'}
  variant={ctrlActive ? 'solid' : 'outline'}
  color={ctrlActive ? 'primary' : 'surface'}
/>

<!-- Event log -->
{#each eventLog as log (log)}
  <p class="text-sm">{log}</p>
{/each}

Options

OptionTypeDefault
shortcutsRecord<string, (e: KeyboardEvent) => void>-
targetEventTargetwindow
enabledbooleantrue
preventDefaultbooleanfalse
captureModifiersbooleanfalse
repeatbooleanfalse

Return Values

NameTypeDefault
isPressed(key: string) => boolean-
pressedKeysReadonlySet<string>-