VOOZH about

URL: https://deepwiki.com/hypervel/prompts/8.1-the-base-renderer

⇱ The Base Renderer | hypervel/prompts | DeepWiki


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

The Base Renderer

Purpose and Scope

The Base Renderer (Renderer abstract class) provides the foundation for all theme-specific prompt renderers in hypervel/prompts. It implements a string accumulation pattern where rendering methods progressively build output text, which is then converted to a string for terminal display. This class defines the common interface and utility methods that all concrete renderers (SelectPromptRenderer, MultiSelectPromptRenderer, etc.) inherit and use.

For information about how specific prompt types implement rendering logic, see Prompt-Specific Renderers. For details on the Termwind styling integration, see Termwind Integration.

Sources: src/Themes/Default/Renderer.php1-104


Class Structure and Abstract Design

The Renderer class is declared as an abstract class that implements PHP's Stringable interface. This design enforces that all theme-specific renderers can be cast to strings while allowing each renderer to implement its own __invoke() method for state-based rendering.


Design Rationale:

AspectImplementationPurpose
Abstract classCannot be instantiated directlyForces implementation through theme-specific subclasses
Stringable interfaceImplements __toString()Enables string casting for output to terminal
Protected methodsline(), warning(), error(), etc.Provides utilities for child classes without exposing public API
Prompt dependencyConstructor injectionGrants renderers access to prompt state, terminal info, and configuration

Sources: src/Themes/Default/Renderer.php12-27


Output Accumulation Pattern

The renderer uses a progressive accumulation pattern where each rendering method appends to a protected $output string property rather than returning strings directly. This enables a fluent interface and defers the actual output until string conversion.


The line() Method

The line() method is the fundamental building block for output accumulation:


Behavior:

  • Appends the message to $output with a platform-appropriate newline (PHP_EOL)
  • Returns $this for method chaining
  • Does not apply any styling or formatting to the message

Sources: src/Themes/Default/Renderer.php32-37

The newLine() Method

The newLine() method adds blank lines to the output:


Parameters:

  • $count: Number of blank lines to insert (default: 1)

Use case: Creating vertical spacing between prompt sections (e.g., separating the label from options)

Sources: src/Themes/Default/Renderer.php42-47


Text Formatting Methods

The base renderer provides four specialized formatting methods that combine output accumulation with visual styling. These methods use the Colors trait to apply ANSI color codes.

Method Overview

MethodIconColorUse Case
warning()YellowNon-critical issues or reminders
error()RedValidation errors or failures
hint()NoneGrayHelp text or instructions
when()N/AN/AConditional rendering logic

warning() Method

Renders a yellow warning message with a warning icon:


Visual Output: ⚠ Your message here (in yellow)

Sources: src/Themes/Default/Renderer.php52-55

error() Method

Renders a red error message with a warning icon:


Visual Output: ⚠ Your message here (in red)

Sources: src/Themes/Default/Renderer.php60-63

hint() Method

Renders a gray hint message with automatic truncation:


Special behaviors:

  • Returns early if message is empty (no-op)
  • Automatically truncates message to fit terminal width minus 6 characters (accounting for indentation)
  • Uses Truncation trait's truncate() method
  • Accesses terminal width via $this->prompt->terminal()->cols()

Visual Output: Your hint text here (in gray, truncated if necessary)

Sources: src/Themes/Default/Renderer.php68-77

when() Method

Provides conditional rendering with optional else callback:


Parameters:

  • $value: Condition to evaluate (uses truthy/falsy logic)
  • $callback: Function called if condition is true, receives $this as argument
  • $default: Optional function called if condition is false

Usage Example:


Sources: src/Themes/Default/Renderer.php84-93


Trait Composition

The base renderer uses two traits to incorporate cross-cutting concerns without inheritance complexity:


Colors Trait

The Colors trait provides 26 methods for ANSI text and background colors. The renderer uses several key methods:

MethodPurposeUsed In
yellow()Warning messageswarning()
red()Error messageserror()
gray()Hint texthint()
dim(), bold()Text emphasisAvailable to child renderers

For complete documentation of color methods, see ANSI Colors and Styling.

Sources: src/Themes/Default/Renderer.php14

Truncation Trait

The Truncation trait provides text fitting methods that ensure output doesn't exceed terminal width:

  • truncate(string $text, int $width): string: Truncates text to specified width, handling multi-byte characters correctly
  • Used primarily in hint() method to prevent text overflow

For complete documentation of truncation methods, see Text Truncation.

Sources: src/Themes/Default/Renderer.php15


String Conversion with __toString()

The __toString() method is responsible for converting the accumulated output into a final string with appropriate spacing. This method is called automatically when the renderer is cast to a string or echoed.


Spacing Logic

The method implements a sophisticated spacing algorithm:


Leading Newlines:

  • Target: Ensure 2 newlines before prompt output
  • Logic: max(2 - $this->prompt->newLinesWritten(), 0)
  • If previous output already has newlines, reduces leading space accordingly
  • Never goes negative (minimum 0 newlines)

Trailing Newline:

  • Added only when prompt state is 'submit' or 'cancel'
  • Omitted for 'active' and 'error' states (prompt continues to display)
  • Creates visual separation after prompt completion

State-Based Rendering

Prompt StateLeading NewlinesTrailing NewlinePurpose
initial0-2 (adaptive)NoPrompt first appears
active0 (redraws)NoUser is interacting
error0 (redraws)NoValidation failed, showing error
submit0-2 (adaptive)YesUser submitted, finalize output
cancel0-2 (adaptive)YesUser canceled, finalize output

Sources: src/Themes/Default/Renderer.php98-103


Integration with Prompt Instance

The renderer maintains a protected reference to the Prompt instance that created it, enabling access to:


Constructor Injection


This uses PHP 8.0+ constructor property promotion, which simultaneously:

  1. Declares the property: protected Prompt $prompt
  2. Assigns the parameter: $this->prompt = $prompt

Sources: src/Themes/Default/Renderer.php25-27

Common Prompt Access Patterns

Child renderers frequently access prompt data through the injected instance:

Access PatternPurposeExample
$this->prompt->labelGet prompt labelDisplay question text
$this->prompt->valueGet current valueShow user input
$this->prompt->stateCheck prompt stateRender differently per state
$this->prompt->errorGet validation errorDisplay error message
$this->prompt->terminal()->cols()Get terminal widthTruncate text appropriately
$this->prompt->newLinesWritten()Get spacing infoCalculate leading newlines

Usage by Prompt-Specific Renderers

Concrete renderer implementations extend this base class and utilize its methods. Here's how the pattern works:


Key Points:

  1. Instantiation: Prompts create renderer instances via renderTheme() method
  2. State-Based Rendering: Renderers implement __invoke() that uses match expressions to render differently based on prompt state
  3. Method Chaining: Renderer methods return $this, enabling fluent interfaces
  4. String Conversion: Prompts cast renderers to strings for terminal output

Example Pattern (conceptual):


For detailed information on how specific renderers implement state-based rendering logic, see Prompt-Specific Renderers.

Sources: src/Themes/Default/Renderer.php1-104


Summary

The Renderer abstract class serves as the foundation for hypervel/prompts' theming system. Its key characteristics:

AspectImplementation
Design PatternAbstract base class with protected utilities
Output ModelProgressive string accumulation via $output property
InterfaceImplements Stringable for automatic string conversion
CompositionUses Colors and Truncation traits for cross-cutting concerns
DependenciesRequires Prompt instance for state and terminal access
Method StyleFluent interface with self return types for chaining
ExtensibilityChild classes implement __invoke() for state-based rendering

This architecture separates presentation logic from prompt behavior, enabling multiple themes while maintaining consistent rendering utilities across all prompt types.

Sources: src/Themes/Default/Renderer.php1-104