Overview

onKeyDown and onKeyUp attach global listeners on window, scoped to the component lifetime. Ideal for shortcuts that should be active while a view is mounted.

Handlers receive the native KeyboardEvent and may return a cleanup function. Listeners are removed automatically on unmount.

Keyboard hooks

API
Event
Notes
onKeyDown(fn) keydown Most common for shortcuts (Escape, Cmd+K, etc.).
onKeyUp(fn) keyup Useful for modifier release (e.g. Shift for multi-select).

onKeyDown — global key listener

onKeyDown listens for keydown events on the window. The listener is automatically removed when the component unmounts — no manual removeEventListener needed.

import { html, atom, onKeyDown, renderApp } from 'mates';

const KeyboardDemo = () => {
const lastKey = atom('—');
const count = atom(0);

// Listens on window.keydown; auto-removes listener on unmount
onKeyDown((e) => {
lastKey.set(e.key === ' ' ? 'Space' : e.key);
count.set(n => n + 1);
});

return () => html`
<p class="muted">Click the preview and press any key</p>
<h1>${lastKey()}</h1>
<span class="tag">${count()} key${count() === 1 ? '' : 's'} pressed</span>
`;
};
renderApp(KeyboardDemo, document.getElementById('app'));