keydown

Keyboard event stream that emits only keydown events. Shares underlying listeners per EventTarget.

Terminal window
npm install --save cereb

Basic Usage

import { keydown } from "cereb";
keydown(window).on((signal) => {
console.log("Key pressed:", signal.value.code);
});

Signature

function keydown(target: EventTarget, options?: KeydownOptions): Stream<KeyboardSignal>

Options

OptionTypeDefaultDescription
codeKeyCode | KeyCode[]-Filter by physical key code(s)
modifiersModifierKey[]-Filter by modifier keys (OR logic)
preventDefaultbooleantrueCall preventDefault on matching events
allowRepeatbooleanfalseAllow repeated keydown events

Signal Value

PropertyTypeDescription
phase"down"Always “down” for keydown
keystringLogical key value (e.g., ”+”, “a”, “Meta”)
codestringPhysical key code (e.g., “Equal”, “KeyA”)
repeatbooleanTrue if repeated from holding key
altKeybooleanAlt key pressed
ctrlKeybooleanCtrl key pressed
metaKeybooleanMeta (Cmd/Win) key pressed
shiftKeybooleanShift key pressed
originalEventKeyboardEventOriginal DOM event

Examples

Zoom with +/- Keys

keydown(window, { code: ["Equal", "Minus"] }).on((signal) => {
const zoomIn = signal.value.code === "Equal";
setScale(scale * (zoomIn ? 1.2 : 0.8));
});

Undo/Redo Shortcut

// Cmd+Z / Ctrl+Z for undo
keydown(window, {
code: "KeyZ",
modifiers: ["meta", "ctrl"]
}).on(handleUndo);
// Cmd+Shift+Z / Ctrl+Shift+Z for redo
keydown(window, {
code: "KeyZ",
modifiers: ["meta", "ctrl"]
}).on((signal) => {
if (signal.value.shiftKey) {
handleRedo();
}
});

Allow Key Repeat

// Continuous scrolling while holding arrow key
keydown(window, {
code: ["ArrowUp", "ArrowDown"],
allowRepeat: true
}).on((signal) => {
const direction = signal.value.code === "ArrowUp" ? -1 : 1;
scroll(direction * 10);
});