Skip to content
Sveltier
Mode
Primitives

Keyboard

Bind keys the same way in every component, and let users jump through long lists by typing.

Typeahead

In a menu, listbox or tree, typing moves focus to the next item whose label starts with what was typed. Keystrokes close together build one search, and repeating a character cycles through the items that start with it.

  • Australian dollar
  • Canadian dollar
  • Euro
  • Japanese yen
  • Pound sterling
  • Singapore dollar
  • Swiss franc
  • US dollar

Selected: Euro. Tab in, then type "s" twice, or "sw", and press Enter.

Currency.svelte
<script>
  import { rovingFocus, typeahead } from 'sveltier';
</script>

<ul role="listbox" aria-label="Currency" {@attach rovingFocus({ orientation: 'vertical' })} {@attach typeahead()}>
  <li role="option" data-sv-item aria-selected="true">Euro</li>
  <li role="option" data-sv-item aria-selected="false">Pound sterling</li>
  …
</ul>
NameTypeDefaultDescription
itemsstring'[data-sv-item]'Selector for the items inside the container.
timeoutnumber500How long typed characters keep building one search, in ms.
onMatch(item: HTMLElement) => voidfocus the itemWhat a match does.

Key maps

keymap() binds keys to handlers and prevents the browser's default only for keys it handled, so everything else keeps working. Forward and backward arrows follow the writing direction, which keeps sliders and tabs right in right-to-left layouts.

Allocation.svelte
<script>
  import { keymap } from 'sveltier';
  let value = $state(50);
  const step = (by) => () => (value = Math.min(100, Math.max(0, value + by)));
</script>

<!-- ArrowForward and ArrowBackward follow the writing direction. -->
<div
  role="slider"
  tabindex="0"
  aria-label="Allocation"
  aria-valuenow={value}
  {@attach keymap({
    ArrowForward: step(1),
    ArrowBackward: step(-1),
    PageUp: step(10),
    PageDown: step(-10),
    Home: () => (value = 0),
    End: () => (value = 100)
  })}
>
  {value}%
</div>
NameTypeDescription
keymap(map)(map: Record<string, KeyHandler>) => AttachmentCalls the handler bound to a key combination and prevents the default when it ran. A handler returning false lets the event through.
combinations'Ctrl+Alt+Shift+Meta+Key'Modifiers in that order, then the event.key name. Shift is left out for characters ("?", not "Shift+/"). ArrowForward and ArrowBackward follow the writing direction.