VOOZH about

URL: https://deepwiki.com/hypervel/prompts/9-reusable-traits-and-concerns

⇱ Reusable Traits and Concerns | hypervel/prompts | DeepWiki


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

Reusable Traits and Concerns

Purpose and Scope

This page provides an overview of the trait-based architecture used throughout the hypervel/prompts library. The library employs PHP traits, organized in the Hypervel\Prompts\Concerns namespace, to provide reusable functionality that prompt components and display elements can compose as needed.

This page introduces the architectural pattern and catalogs the available traits. For detailed documentation of specific traits, see the following pages:

For testing-related traits, see 10.1 Testing with Mocked Terminal I/O. For fallback mechanisms, see 10.2 Fallback Implementations.

Trait-Based Composition Architecture

The library follows a composition-over-inheritance design pattern. Instead of deep class hierarchies, prompt components and display elements mix in traits to acquire specific capabilities. This approach provides:

  • Modularity: Each trait encapsulates a single concern
  • Reusability: Multiple components share the same trait implementations
  • Flexibility: Components include only the traits they need
  • Testability: Traits can be tested independently

The base Prompt class provides core functionality, while traits extend specific components with additional capabilities.

Trait Composition in Components


Sources: src/SelectPrompt.php13 src/Concerns/Colors.php1-208

Trait Catalog

The following traits are available in the Hypervel\Prompts\Concerns namespace:

TraitPurposePrimary UsersPage
ScrollingNavigate through paginated lists with keyboard controlsSelectPrompt, MultiSelectPrompt, SearchPrompt, MultiSearchPrompt, SuggestPrompt9.1
ColorsApply ANSI color codes and text stylingRenderer, various components9.2
CursorControl terminal cursor positioningPrompt base class9.3
EraseClear terminal screen or linesPrompt base class9.3
TruncationTruncate and wrap text to fit terminal widthSearchPrompt, Renderer9.4
EventsEvent-driven interaction and keyboard input handlingPrompt base class (inherited by all prompts)9.5
TypedValueTrack typed input and cursor positionTextPrompt, TextareaPrompt, PasswordPrompt, SearchPrompt, SuggestPrompt, MultiSearchPrompt9.6
DrawsBoxesRender framed containers with bordersTheme renderers8.2
DrawsScrollbarsRender scrollbar indicators for viewportsTheme renderers8.2
ThemesSelect and instantiate renderersPrompt components8
TermwindRender HTML-like markup to terminalRenderer base class8.3
InteractivityDetect interactive terminal modePrompt base class10.2
FakesInputOutputMock terminal I/O for testingTest utilities10.1
FallbackProvide alternative implementationsVarious components10.2

Sources: src/SelectPrompt.php13 src/Concerns/Colors.php1-208

Trait Categories

Traits can be grouped into functional categories based on their primary purpose:

Behavioral Traits

Traits: Scrolling, TypedValue, Events, Fallback

These traits manage how users interact with prompts and how prompts respond to input.

  • Scrolling: Manages highlighted, firstVisible indices for navigable lists (SelectPrompt, MultiSelectPrompt, SearchPrompt)
  • TypedValue: Tracks user input and cursor position in text-based prompts (TextPrompt, SearchPrompt)
  • Events: Observer pattern with on(), emit(), clearListeners() methods (used by Prompt base class)
  • Fallback: Conditional alternative implementations for non-interactive environments

Behavioral Trait Usage


Sources: src/SelectPrompt.php13 src/Concerns/Colors.php1-208

Visual Traits

Traits: Colors, Truncation, Cursor, Erase, DrawsBoxes, DrawsScrollbars

These traits control how content is visually formatted and displayed in the terminal.

  • Colors: 26 methods for ANSI text/background colors (red, green, blue, etc.), plus styles (bold, dim, underline, strikethrough)
  • Truncation: Terminal width-aware text fitting with cursor placement
  • Cursor: Hide/show/move cursor operations (hideCursor, showCursor, moveCursor)
  • Erase: Line and screen clearing operations (eraseDown, eraseLine)
  • DrawsBoxes: Framed containers with titles and borders
  • DrawsScrollbars: Viewport scrolling indicators for long lists

Visual Trait Usage


Sources: src/Concerns/Colors.php1-208

Integration Traits

Traits: Themes, Termwind, Interactivity, FakesInputOutput

These traits integrate with external systems and frameworks.

  • Themes: Renderer selection and instantiation via getRenderer() method
  • Termwind: HTML-like styling via Termwind library integration
  • Interactivity: Detects if terminal supports interactive mode via interactive() static property
  • FakesInputOutput: Mockery-based testing infrastructure for mocking terminal I/O

Sources: src/SelectPrompt.php13 src/Concerns/Colors.php1-208

Trait Composition Patterns

Components typically use multiple traits together to achieve their functionality. Here are common composition patterns:

Pattern 1: List-Based Selection Prompts

Components that display scrollable lists use the Scrolling trait. Example: SelectPrompt

SelectPrompt Trait Composition


The SelectPrompt constructor at src/SelectPrompt.php55-62 registers key handlers that call methods from the Scrolling trait:

  • Key::UPhighlightPrevious()
  • Key::DOWNhighlightNext()
  • Key::HOMEhighlight(0)
  • Key::ENDhighlight(count - 1)
  • Key::ENTERsubmit()

Sources: src/SelectPrompt.php13-62

Pattern 2: Text Input Prompts

Components that capture typed text use the TypedValue trait. This trait provides properties and methods for managing user text input.

TypedValue Trait Composition


The TypedValue trait's trackTypedValue() method registers comprehensive keyboard handlers for text manipulation, cursor movement, and text deletion. These handlers update the typedValue and cursorPosition properties as the user types.

Sources: src/SelectPrompt.php13

Pattern 3: Search Prompts (Multiple Traits)

Search prompts combine multiple traits for complex interaction: text input, list navigation, and text formatting.

SearchPrompt Multi-Trait Composition


The SearchPrompt class demonstrates trait composition for complex functionality:

  1. User types query → TypedValue trait manages input
  2. Input triggers filtering → Updates available options
  3. User navigates results → Scrolling trait manages selection
  4. Options displayed → Truncation trait fits text to terminal width

Sources: src/SelectPrompt.php13

Key Properties and Methods

Each trait exposes properties and methods that become part of the using class. Here are the key interfaces:

Scrolling Trait Interface

The Scrolling trait provides list navigation with viewport management. Used by: SelectPrompt, MultiSelectPrompt, SearchPrompt, MultiSearchPrompt, SuggestPrompt.

Public Properties:

PropertyTypeDescription
$scrollintNumber of visible items in viewport
$highlighted?intIndex of currently highlighted option
$firstVisibleintIndex of first visible item in viewport

Public Methods:

MethodPurpose
initializeScrolling(?int $highlighted)Initialize scrolling state with optional starting position
highlight(?int $index)Set highlighted index and adjust viewport
highlightPrevious(int $total, bool $allowNull)Move highlight up, wrapping if needed
highlightNext(int $total, bool $allowNull)Move highlight down, wrapping if needed
scrollToHighlighted(int $total)Adjust viewport to show highlighted item

See src/SelectPrompt.php55-62 for usage example where these methods are called from key event handlers.

Sources: src/SelectPrompt.php13-62

TypedValue Trait Interface

The TypedValue trait manages text input with cursor positioning. Used by: TextPrompt, TextareaPrompt, PasswordPrompt, SearchPrompt, SuggestPrompt, MultiSearchPrompt.

Public Properties:

PropertyTypeDescription
$typedValuestringCurrent typed text content
$cursorPositionintCursor position (0-based index)

Public Methods:

MethodPurpose
trackTypedValue(string $default, bool $submit, ?callable $ignore, bool $allowNewLine)Initialize input tracking with default value and register key handlers
value()Return current typed value
addCursor(string $value, int $cursorPosition, ?int $maxWidth)Insert visual cursor indicator at position

Sources: src/SelectPrompt.php13

Colors Trait Interface

The Colors trait provides ANSI escape sequences for terminal styling. Used by: Renderer base class and various components.

Text Color Methods: black(), red(), green(), yellow(), blue(), magenta(), cyan(), white(), gray()

Background Color Methods: bgBlack(), bgRed(), bgGreen(), bgYellow(), bgBlue(), bgMagenta(), bgCyan(), bgWhite()

Style Methods: reset(), bold(), dim(), italic(), underline(), inverse(), hidden(), strikethrough()

All methods accept a string $text parameter and return the text wrapped in ANSI escape codes. For example:

  • $this->red('error') returns "\e<FileRef file-url="https://github.com/hypervel/prompts/blob/2e218156/31merror\\e[39m\"\n- $this->bold('title') returns \"\\e[1mtitle\\e[22m\"\n\nSee [src/Concerns/Colors.php#L12-L207" min=12 max=207 file-path="31merror\e[39m"\n- $this->bold('title')returns"\e[1mtitle\e[22m"`\n\nSee [src/Concerns/Colors.php">Hii for the complete implementation.

Sources: src/Concerns/Colors.php1-208

Trait Dependencies and Method Requirements

Traits may require specific methods to exist on the using class. These dependencies are typically satisfied by the Prompt base class or other traits.

Trait Dependency Graph


Dependency Details:

TraitRequired MethodsProvided ByPurpose
Scrollingterminal()PromptAccess terminal dimensions for viewport calculations
TypedValueon(), submit()Events trait, PromptRegister key handlers and submit on Enter
DrawsBoxesNone-Self-contained rendering utilities
DrawsScrollbarsNone-Self-contained rendering utilities
ColorsNone-Pure ANSI escape code generation
CursorNone-Pure ANSI escape code generation
EraseNone-Pure ANSI escape code generation

The Prompt base class uses the Events, Cursor, Erase, Fallback, and Interactivity traits, making these capabilities available to all prompt subclasses.

Sources: src/SelectPrompt.php11-62 src/Concerns/Colors.php1-208

Code Example: SelectPrompt Trait Usage

The SelectPrompt class demonstrates practical trait composition. It uses the Scrolling trait to manage list navigation.

Class Declaration with Trait:


Initializing Scrolling State: The constructor at src/SelectPrompt.php43-53 initializes the Scrolling trait:

  • If a default value is provided, finds its index and calls initializeScrolling($index)
  • Calls scrollToHighlighted() to adjust the viewport
  • Otherwise calls initializeScrolling(0) to start at the first item

Registering Key Handlers: The constructor at src/SelectPrompt.php55-62 registers key event handlers that call Scrolling trait methods:


Accessing Scrolling Properties: The visible() method at src/SelectPrompt.php96-99 uses $this->firstVisible and $this->scroll properties provided by the trait:


Sources: src/SelectPrompt.php13-99

Design Principles

The trait system follows these design principles:

  1. Single Responsibility: Each trait handles one specific concern
  2. No State Coupling: Traits don't depend on each other's state directly
  3. Method Contracts: Traits may require specific methods on the using class
  4. Property Exposure: Traits expose public properties that renderers can access
  5. Event-Driven: Interaction traits integrate with the Events system
  6. Terminal-Aware: Traits respect terminal dimensions and capabilities

Renderer Integration

Traits often expose properties that renderers consume to format output. The theme system provides renderer contracts that expect specific trait properties:

Renderer ContractExpected PropertiesSource Trait
ScrollingRendererhighlighted, firstVisible, scrollScrolling
Theme methodsColor and styling preferencesColors
Various rendererstypedValue, cursorPositionTypedValue

Sources: src/Concerns/Scrolling.php7-8

Next Steps

For detailed documentation of each trait:

For information on creating components that use these traits, see Interactive Prompts and Display Components.