VOOZH about

URL: https://deepwiki.com/hypervel/prompts/4.1-the-prompt-lifecycle

⇱ The Prompt Lifecycle | hypervel/prompts | DeepWiki


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

The Prompt Lifecycle

Purpose and Scope

This document details the execution flow of the prompt() method in the base Prompt class, which orchestrates the complete lifecycle of an interactive prompt from initialization through user input handling to final submission. This covers the core rendering loop, terminal configuration, input processing, and cleanup mechanisms that apply to all prompt types.

For information about prompt state management and validation logic, see State Management and Validation. For details on terminal integration and raw mode handling, see Terminal Integration. For concrete prompt implementations, see Interactive Prompts.


Overview: The prompt() Method Entry Point

The prompt() method src/Prompt.php104-161 is the primary entry point for all interactive prompts. It coordinates environment checks, terminal configuration, the rendering loop, and cleanup. The method returns the final user input value or throws an exception for cancellation/reversion.

High-Level Execution Flow


Sources: src/Prompt.php104-161


Lifecycle Phases

Phase 1: Pre-Flight Checks and Initialization

Before entering the interactive loop, the prompt performs several initialization steps:

StepMethodPurpose
1. Capture NewlinescapturePreviousNewLines() src/Prompt.php207-212Records how many newlines were written by previous output for proper cursor positioning
2. Fallback CheckshouldFallback()Determines if the prompt should use fallback mode based on Fallback trait configuration
3. Interactivity Checkstream_isatty(STDIN) src/Prompt.php113Verifies the terminal supports interactive input; returns default() if non-interactive
4. Environment CheckcheckEnvironment() src/Prompt.php433-438Validates OS compatibility (currently rejects Windows without WSL)

Sources: src/Prompt.php107-119 src/Prompt.php207-212 src/Prompt.php433-438


Phase 2: Terminal Configuration

The prompt configures the terminal for raw mode input, enabling character-by-character reading without buffering:


Terminal Raw Mode Configuration:

  • -icanon: Disable canonical mode (line buffering)
  • -isig: Disable signal generation (Ctrl+C handled in code)
  • -echo: Disable character echo (prompts control display)

The configuration is wrapped in a try-catch src/Prompt.php121-128 to gracefully fall back if TTY control fails (e.g., piped input, restricted environments).

Sources: src/Prompt.php121-131


Phase 3: The Rendering Loop

The core of the prompt lifecycle is the rendering loop, implemented via the runLoop() method:


The runLoop() Implementation src/Prompt.php168-186:


Sources: src/Prompt.php168-186


Phase 3.1: The Loop Callback

The callback passed to runLoop() src/Prompt.php133-155 orchestrates input handling and rendering:


Key Handling Logic:

  1. handleKeyPress(key) src/Prompt.php327-366: Processes the key, updates state, emits events, returns false to exit loop
  2. render() src/Prompt.php281-310: Updates the terminal display with current prompt state
  3. Exit Conditions:
    • handleKeyPress() returns false (e.g., Enter key pressed)
    • Key::CTRL_C pressed: cancellation
    • Key::CTRL_U pressed with revertUsing set: form reversion

Sources: src/Prompt.php133-155 src/Prompt.php327-366


Phase 3.2: Input Processing and State Management

The handleKeyPress() method src/Prompt.php327-366 manages state transitions and delegates to prompt-specific key handlers:

StateTransitionTrigger
erroractiveError clearedAny key press while in error state
activesubmitUser submitsPrompt-specific submit logic (e.g., Enter key)
activecancelUser cancelsKey::CTRL_C pressed
activecancelUser revertsKey::CTRL_U pressed (with revertUsing callback)
activeerrorInvalid reversionKey::CTRL_U pressed without revertUsing callback

Event Emission:
The method emits a 'key' event src/Prompt.php333 with the pressed key, enabling prompt subclasses and external code to observe input via the Events trait.

Validation:
If validation has been performed ($this->validated === true), each key press triggers revalidation src/Prompt.php361-363 to provide real-time feedback.

Sources: src/Prompt.php327-366


Phase 4: Submission and Cleanup

When the loop exits, the prompt completes submission and performs cleanup:


Submission Process src/Prompt.php315-322:

  1. Retrieve the prompt's current value via value()
  2. Apply transformation via transform() callback if set src/Prompt.php370-378
  3. Validate the transformed value src/Prompt.php391-420
  4. Set state to 'submit' if valid, or 'error' if invalid

Cleanup src/Prompt.php158-160:

  • The finally block ensures clearListeners() is called to remove event callbacks
  • The destructor src/Prompt.php443-448 restores cursor visibility and terminal TTY settings

Sources: src/Prompt.php315-322 src/Prompt.php370-386 src/Prompt.php158-160 src/Prompt.php443-448


Rendering: The render() Method

The render() method src/Prompt.php281-310 efficiently updates the terminal display by comparing frames:


Initial Render src/Prompt.php291-297:

  • When state === 'initial', the frame is written directly
  • State transitions to 'active'

Subsequent Renders src/Prompt.php300-309:

  • Calculate the previous frame height
  • Move cursor up to the start of the previous frame
  • Erase from cursor to end of screen
  • Write only the visible lines of the new frame
  • Accounts for terminal height to prevent scrolling issues

Frame Comparison:
If the new frame matches prevFrame, rendering is skipped src/Prompt.php287-289 to avoid unnecessary terminal I/O.

Sources: src/Prompt.php281-310


Alternative Lifecycle: Progress Component

The Progress class src/Progress.php implements a specialized lifecycle without the interactive input loop:


Progress Lifecycle Methods

MethodPurposeState Transition
start() src/Progress.php100-116Initializes progress bar, sets up signal handling, hides cursorinitialactive
advance(int) src/Progress.php121-130Increments progress counter, triggers re-renderStays in active
finish() src/Progress.php135-141Completes progress bar, restores cursor and signalsactivesubmit
map(Closure) src/Progress.php59-95Orchestrates full lifecycle: start → iterate → advance → finishManages full flow

Signal Handling:
Progress bars install a SIGINT handler src/Progress.php104-111 to gracefully handle Ctrl+C interruption, setting state = 'cancel' and rendering before exit.

The map() Method src/Progress.php59-95:

  • The primary API for progress bars
  • Automatically calls start(), iterates through steps, calls advance(), and calls finish()
  • Wraps iteration in try-catch to ensure proper cleanup on exceptions

No Input Loop:
Unlike interactive prompts, Progress overrides prompt() src/Progress.php184-187 to throw an exception, as it does not accept user input.

Sources: src/Progress.php59-95 src/Progress.php100-116 src/Progress.php121-130 src/Progress.php135-141 src/Progress.php184-187


State Lifecycle Summary

The complete state machine for interactive prompts:


State Descriptions

StateDescriptionWhen Set
initialPrompt created but not yet renderedConstructor (default value) src/Prompt.php29
activePrompt is displayed and accepting inputFirst render src/Prompt.php294 or after error cleared src/Prompt.php330
errorValidation failed, error message displayedValidation fails src/Prompt.php317 src/Prompt.php396 src/Prompt.php417
submitUser has submitted valid inputSuccessful validation src/Prompt.php320
cancelUser cancelled or reverted the promptCTRL_C src/Prompt.php356 or CTRL_U src/Prompt.php347 pressed

Sources: src/Prompt.php29 src/Prompt.php294 src/Prompt.php315-322 src/Prompt.php327-366


Code Entity Reference

Key Methods and Their Roles

MethodClassLine ReferenceRole
prompt()Promptsrc/Prompt.php104-161Main entry point, orchestrates entire lifecycle
runLoop(callable)Promptsrc/Prompt.php168-186Input reading loop, invokes callback per key press
handleKeyPress(string)Promptsrc/Prompt.php327-366Processes individual key, manages state transitions
render()Promptsrc/Prompt.php281-310Updates terminal display efficiently
submit()Promptsrc/Prompt.php315-322Validates and transitions to submit state
capturePreviousNewLines()Promptsrc/Prompt.php207-212Records output state for cursor positioning
checkEnvironment()Promptsrc/Prompt.php433-438Validates OS compatibility
transformedValue()Promptsrc/Prompt.php383-386Applies transformation callback to value
validate(mixed)Promptsrc/Prompt.php391-420Validates value and sets error state

Terminal Control Methods (via Traits)

MethodTraitPurpose
hideCursor()CursorHides terminal cursor during prompt
restoreCursor()CursorShows cursor after prompt completion
moveCursorUp(int)CursorRepositions cursor for frame updates
moveCursorToColumn(int)CursorMoves cursor horizontally
eraseDown()EraseClears terminal from cursor to end

Sources: src/Prompt.php


Integration Points

FormBuilder Integration

The lifecycle integrates with FormBuilder through the reversion mechanism:

Event System Integration

The lifecycle emits events at key points:

  • 'key' event src/Prompt.php333: Fired on each key press with the key value
  • Listeners registered via on(string, Closure) from Events trait
  • Cleanup via clearListeners() src/Prompt.php159 in finally block

Sources: src/Prompt.php263-276 src/Prompt.php333 src/Prompt.php159