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:
- Add new event types:
onkeydown
onkeypress
onkeyup
- 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;
}
- 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
- Create
KeyboardEvent class extending Event
- Modify TTY input handling to create and emit keyboard events
- Add JavaScript bindings for the new event types
- Add TypeScript type definitions
- 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
Problem
Currently, keyboard input handling in Bun requires using low-level
process.stdinwith 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:
onkeydownonkeypressonkeyupImplementation Details
KeyboardEventclass extendingEventBenefits
Example Usage
Related Work
ProcessBindingTTYWrap.cppJSEventEmitterEvent.h