Skip to content

Add support for keyboard events (onkeydown, onkeypress, onkeyup) #4

Description

@negentropi

Problem

Currently, keyboard input handling in Bun requires using low-level process.stdin with raw mode, which is less intuitive and harder to work with compared to browser-like keyboard events.

Proposed Solution

Implement browser-compatible keyboard events for Bun:

  1. Add new event types:
  • onkeydown
  • onkeypress
  • onkeyup
  1. Implement KeyboardEvent interface with properties:
interface KeyboardEvent extends Event {
    key: string;
    code: string;
    keyCode: number;
    repeat: boolean;
    shiftKey: boolean;
    ctrlKey: boolean;
    altKey: boolean;
    metaKey: boolean;
}
  1. Support both handler assignment and event listener patterns:
// Handler pattern
process.onkeydown = (e) => {
    if (e.key === ' ') {
        console.log('Spacebar pressed');
    }
};

// Event listener pattern
process.addEventListener('keydown', (e) => {
    if (e.key === ' ') {
        console.log('Spacebar pressed');
    }
});

Implementation Details

  1. Create KeyboardEvent class extending Event
  2. Modify TTY input handling to create and emit keyboard events
  3. Add JavaScript bindings for the new event types
  4. Add TypeScript type definitions
  5. Add tests for the new functionality

Benefits

  • More intuitive API for handling keyboard input
  • Better compatibility with browser-based code
  • Easier migration path for web developers
  • More consistent event handling across the platform

Example Usage

// Current approach
process.stdin.setRawMode(true);
process.stdin.on('data', (e) => {
    if (e[0] === 32) {
        console.log('Spacebar pressed');
    }
});

// Proposed approach
process.onkeydown = (e) => {
    if (e.key === ' ') {
        console.log('Spacebar pressed');
    }
};

Related Work

  • Current keyboard handling in ProcessBindingTTYWrap.cpp
  • Event system in JSEventEmitter
  • Existing event types in Event.h

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions