VOOZH about

URL: https://deepwiki.com/hypervel/prompts/10.3-key-handling-and-input-processing

⇱ Key Handling and Input Processing | hypervel/prompts | DeepWiki


Loading...
Last indexed: 7 February 2026 (2e2181)
Menu

Key Handling and Input Processing

This document describes the low-level keyboard input handling mechanisms in the hypervel/prompts library. It covers the Key class constants that represent terminal key sequences and the input processing logic used by text-based prompts to handle cursor movement, text editing, and keyboard events.

For information about the higher-level TypedValue trait that uses these key handling mechanisms, see Typed Value Management. For details on the event system that dispatches key events, see Event System and Interactivity.

The Key Class

The Key class src/Key.php7-115 serves as a central registry of terminal key sequence constants. Terminal applications receive keyboard input as escape sequences (ANSI codes) or control characters, not as high-level key names. This class maps these low-level sequences to semantic constants.

Purpose of the Key Class:

AspectDescription
CentralizationSingle source of truth for all key sequences used throughout the library
AbstractionProvides readable constant names instead of raw escape sequences
Cross-terminal SupportHandles terminal variations (e.g., multiple HOME key sequences)
Type SafetyPHP constants prevent typos and enable IDE autocomplete

Sources: src/Key.php1-115

Key Constant Categories

The Key class organizes constants into several functional categories:


Sources: src/Key.php9-96

Navigation Keys

Navigation keys control cursor position and list scrolling:

ConstantValueDescription
UP"\e<FileRef file-url="https://github.com/hypervel/prompts/blob/2e218156/A\"Up arrow (standard ANSI sequence)

HOME and END Keys

The HOME and END constants are unique in that they are defined as arrays containing multiple possible sequences:


This accommodates terminal emulator inconsistencies where different terminals send different sequences for the same key.

Sources: src/Key.php43-45

Editing Keys

ConstantValueDescription
BACKSPACE"\177"Delete character before cursor (DEL character)
DELETE"\e<FileRef file-url="https://github.com/hypervel/prompts/blob/2e218156/3~\"Delete character at cursor

Control Key Combinations

Control keys provide alternative shortcuts and system functions:

ConstantValuePrimary UseSemantic Meaning
CTRL_C"\x03"Cancel operationSIGINT signal
CTRL_P"\x10"Previous itemUp navigation
CTRL_N"\x0E"Next itemDown navigation
CTRL_F"\x06"ForwardRight/next
CTRL_B"\x02"BackLeft/previous
CTRL_H"\x08"BackspaceAlternative backspace
CTRL_A"\x01"Start of lineHome
CTRL_E"\x05"End of lineEnd
CTRL_D"\x04"End of fileEOF signal
CTRL_U"\x15"Negative responseAffirmation toggle

These control keys follow Unix terminal conventions and provide keyboard-only alternatives to special keys.

Sources: src/Key.php47-96

The oneOf() Helper Method

The Key::oneOf() static method src/Key.php102-114 handles multi-sequence key constants like HOME and END:


Method Signature:


Parameters:

  • $keys: Array of key constants (can include arrays like HOME)
  • $match: The actual key sequence received from terminal

Returns: The matched key sequence or null if no match

Usage Pattern:


This allows code to check multiple possible keys in a single expression while handling the complexity of multi-sequence constants.

Sources: src/Key.php98-114

Input Processing in TypedValue

The TypedValue trait src/Concerns/TypedValue.php9-132 implements the core text input processing logic used by TextPrompt, TextareaPrompt, PasswordPrompt, and search-based prompts.

TypedValue State Management

The trait maintains two critical pieces of state:

PropertyTypePurpose
$typedValuestringThe complete text value entered by the user
$cursorPositionintZero-based index of the virtual cursor within $typedValue

Cursor Position Invariant: 0 <= $cursorPosition <= mb_strlen($typedValue)

The cursor can be positioned at the start (0), at any character position, or at the end (length) of the string.

Sources: src/Concerns/TypedValue.php11-19

The trackTypedValue() Method

The trackTypedValue() method src/Concerns/TypedValue.php24-82 establishes a key event listener that processes all keyboard input:

Method Signature:


Parameters:

ParameterTypeDescription
$defaultstringInitial value and cursor position
$submitboolWhether ENTER submits the prompt
$ignore?callableOptional callback to ignore specific keys
$allowNewLineboolWhether ENTER inserts newline (textarea mode)

Sources: src/Concerns/TypedValue.php24

Key Event Processing Flow


Sources: src/Concerns/TypedValue.php32-81

Cursor Movement Operations

The first phase of key processing handles escape sequences and control keys for cursor movement src/Concerns/TypedValue.php40-47:


Match Expression Details:

The code uses a match expression with Key::oneOf() for multi-sequence constants:

  • Key::LEFT, Key::LEFT_ARROW, Key::CTRL_B → Move cursor left (bounded at 0)
  • Key::RIGHT, Key::RIGHT_ARROW, Key::CTRL_F → Move cursor right (bounded at string length)
  • Key::oneOf([Key::HOME, Key::CTRL_A], $key) → Move cursor to start
  • Key::oneOf([Key::END, Key::CTRL_E], $key) → Move cursor to end
  • Key::DELETE → Delete character at cursor without moving cursor

Sources: src/Concerns/TypedValue.php40-47

Character Buffer Processing

Keys may be buffered (multiple characters received at once), so the handler loops through each character src/Concerns/TypedValue.php52-80:

ENTER Key Behavior


This dual behavior allows:

  • TextPrompt: ENTER submits (default behavior)
  • TextareaPrompt: ENTER inserts newline, requires explicit submit action

Sources: src/Concerns/TypedValue.php58-68

BACKSPACE Operation

The backspace operation src/Concerns/TypedValue.php69-75 removes the character before the cursor:

Before: "Hello|World" (cursor at position 5)
After: "Hell|World" (cursor at position 4)

Implementation:

  1. Check if cursorPosition === 0 (no character to delete)
  2. Extract substring before cursor minus 1: mb_substr($value, 0, $cursorPosition - 1)
  3. Append substring after cursor: mb_substr($value, $cursorPosition)
  4. Decrement cursor position

Special Cases:

  • Key::BACKSPACE ("\177")
  • Key::CTRL_H ("\x08")

Both constants trigger the same backspace behavior.

Sources: src/Concerns/TypedValue.php69-75

Character Insertion

Printable characters (ASCII >= 32) are inserted at the cursor position src/Concerns/TypedValue.php76-78:

Before: "Hello|World" (cursor at position 5, typing 'X')
After: "HelloX|World" (cursor at position 6)

Implementation:

  1. Check ord($key) >= 32 (printable range)
  2. Extract substring before cursor: mb_substr($value, 0, $cursorPosition)
  3. Insert new character: $key
  4. Append substring after cursor: mb_substr($value, $cursorPosition)
  5. Increment cursor position

Sources: src/Concerns/TypedValue.php76-79

Visual Cursor Rendering

The addCursor() method src/Concerns/TypedValue.php95-119 renders the virtual cursor as an inverse-video character:


Key Features:

FeatureImplementation
Cursor DisplayCharacter at cursor position rendered with $this->inverse() styling
Empty PositionSpace character used when cursor is at end or on newline
Width ConstraintIntelligently truncates text before and after cursor to fit $maxWidth
Truncation IndicatorsDim ellipsis () shown when text is truncated
Newline HandlingPreserves PHP_EOL when cursor is on newline character

Truncation Strategy:

  1. Calculate space available before cursor (accounting for cursor width and after text)
  2. If before-text exceeds space, truncate from left with trimWidthBackwards()
  3. Calculate remaining space for after-text
  4. If after-text exceeds space, truncate from right with mb_strimwidth()

Sources: src/Concerns/TypedValue.php95-119

The value() Method

The value() method src/Concerns/TypedValue.php87-90 provides read access to the typed value:


This is the primary interface for prompt classes to retrieve the user's input after submission.

Sources: src/Concerns/TypedValue.php87-90

Integration with Prompt Components


Typical Usage Pattern:

  1. Prompt class calls trackTypedValue() during initialization
  2. Sets up parameters: $submit, $ignore, $allowNewLine
  3. Key events flow through the handler established by trackTypedValue()
  4. Handler updates $typedValue and $cursorPosition based on key input
  5. Renderer calls addCursor() to display current state with visual cursor
  6. On submit, prompt retrieves final value via value()

Sources: src/Concerns/TypedValue.php9-132 src/Key.php1-115

Multibyte String Handling

All string operations use mb_* functions to correctly handle multibyte characters (UTF-8):

OperationFunction UsedPurpose
String lengthmb_strlen()Count characters (not bytes)
Substringmb_substr()Extract character ranges
String splitmb_str_split()Split into character array
Width calculationmb_strwidth()Calculate display width
Width trimmingmb_strimwidth()Truncate by display width

Why This Matters:

  • Single character can be multiple bytes in UTF-8 (e.g., emoji, CJK characters)
  • Cursor position is character-based, not byte-based
  • Display width may differ from character count (e.g., emoji are often 2 cells wide)
  • mbstring extension is a required dependency composer.json

Sources: src/Concerns/TypedValue.php29-130

Summary

The key handling system consists of:

  1. Key Class: Central registry of terminal escape sequences as PHP constants
  2. Key::oneOf(): Helper for matching multi-sequence keys like HOME/END
  3. TypedValue Trait: Text input processing with cursor management
  4. Event-Driven Processing: Key events dispatched through the Events trait
  5. Multibyte Support: Proper handling of UTF-8 characters via mbstring

This architecture enables:

  • Portable key handling across different terminal emulators
  • Sophisticated text editing with cursor navigation
  • Flexible behavior configuration (submit vs newline, key filtering)
  • Visual cursor feedback with intelligent truncation

The system provides the foundation for all interactive text input in the prompts library.

Sources: src/Key.php1-115 src/Concerns/TypedValue.php1-132