0
# Render System
1
2
Console-based rendering engine providing terminal UI control, event handling, and visual presentation for interactive prompts. The render system handles terminal compatibility, visual styling, and user interaction processing with support for customizable themes.
3
4
## Capabilities
5
6
### Console Renderer
7
8
Primary rendering implementation for terminal-based interactive prompts with theme support and cross-platform terminal compatibility.
9
10
```python { .api }
11
class ConsoleRender:
12
"""Console-based renderer for terminal UI with theme support."""
13
14
def __init__(self, theme=None):
15
"""
16
Initialize console renderer.
17
18
Args:
19
theme: Theme instance for visual styling (defaults to Default theme)
20
"""
21
22
def render(self, question, answers: dict | None = None):
23
"""
24
Render a question and collect user input.
25
26
Args:
27
question: Question instance to render and process
28
answers: Previous answers dictionary for dynamic content
29
30
Returns:
31
User's input/selection for the question
32
33
Raises:
34
KeyboardInterrupt: If user cancels with Ctrl+C
35
ValidationError: If input fails validation
36
"""
37
```
38
39
**Usage Examples:**
40
41
```python
42
import inquirer
43
from inquirer.render.console import ConsoleRender
44
from inquirer.themes import GreenPassion
45
46
# Custom renderer with theme
47
render = ConsoleRender(theme=GreenPassion())
48
49
# Use with individual questions
50
question = inquirer.Text('name', message="Your name?")
51
answer = render.render(question)
52
53
# Use with prompt system
54
questions = [
55
inquirer.Text('name', message="Your name?"),
56
inquirer.List('color', message="Favorite color?", choices=['Red', 'Blue', 'Green'])
57
]
58
59
# Each question uses the custom renderer
60
answers = inquirer.prompt(questions, render=render)
61
```
62
63
### Generic Render Interface
64
65
Abstract rendering interface allowing for different UI implementations and render engine swapping.
66
67
```python { .api }
68
class Render:
69
"""Generic render interface with pluggable implementations."""
70
71
def __init__(self, impl=ConsoleRender):
72
"""
73
Initialize render interface.
74
75
Args:
76
impl: Render implementation class (defaults to ConsoleRender)
77
"""
78
79
def render(self, question, answers: dict):
80
"""
81
Render a question using the configured implementation.
82
83
Args:
84
question: Question instance to render
85
answers: Answers dictionary for context
86
87
Returns:
88
User input collected by the implementation
89
"""
90
```
91
92
**Usage Example:**
93
94
```python
95
from inquirer.render import Render, ConsoleRender
96
97
# Default console implementation
98
render = Render()
99
100
# Explicit console implementation
101
render = Render(impl=ConsoleRender)
102
103
# Use with questions
104
question = inquirer.Confirm('proceed', message="Continue?")
105
result = render.render(question, {})
106
```
107
108
## Event System
109
110
Low-level event handling for keyboard input and terminal control.
111
112
### Event Classes
113
114
```python { .api }
115
class Event:
116
"""Base event class."""
117
118
class KeyPressed(Event):
119
"""Keyboard input event."""
120
121
def __init__(self, value: str):
122
"""
123
Create key press event.
124
125
Args:
126
value: Key character or escape sequence
127
"""
128
129
@property
130
def value(self) -> str:
131
"""Key value that was pressed."""
132
133
class Repaint(Event):
134
"""Screen repaint event for UI updates."""
135
136
class KeyEventGenerator:
137
"""Generator for keyboard input events."""
138
139
def __init__(self, key_generator=None):
140
"""
141
Initialize key event generator.
142
143
Args:
144
key_generator: Optional custom key input function
145
"""
146
147
def next(self) -> KeyPressed:
148
"""
149
Get next keyboard input event.
150
151
Returns:
152
KeyPressed event with input value
153
"""
154
```
155
156
**Usage Example:**
157
158
```python
159
from inquirer.events import KeyEventGenerator, KeyPressed, Repaint
160
161
# Create event generator
162
generator = KeyEventGenerator()
163
164
# Process keyboard events
165
while True:
166
event = generator.next()
167
if isinstance(event, KeyPressed):
168
if event.value == '\r': # Enter key
169
break
170
print(f"Key pressed: {event.value}")
171
```
172
173
## Terminal Integration
174
175
The render system integrates with terminal capabilities through the `blessed` library, providing:
176
177
- **Cross-platform support**: Windows, macOS, Linux terminal compatibility
178
- **Color and styling**: Full color palette with style combinations
179
- **Cursor control**: Positioning and visibility management
180
- **Screen management**: Clear screen, line manipulation, scrolling
181
- **Input handling**: Raw keyboard input with special key detection
182
183
### Theme Integration
184
185
Renderers automatically apply theme styling to visual elements:
186
187
```python
188
import inquirer
189
from inquirer.render.console import ConsoleRender
190
from inquirer.themes import RedSolace
191
192
# Create themed renderer
193
themed_render = ConsoleRender(theme=RedSolace())
194
195
# Questions rendered with red theme styling
196
questions = [
197
inquirer.List('action', message="Select action",
198
choices=['Create', 'Update', 'Delete']),
199
inquirer.Confirm('confirm', message="Are you sure?")
200
]
201
202
answers = inquirer.prompt(questions, render=themed_render)
203
```
204
205
## Advanced Rendering
206
207
### Custom Render Implementation
208
209
For specialized use cases, you can create custom render implementations:
210
211
```python
212
from inquirer.render.console import ConsoleRender
213
214
class CustomRender(ConsoleRender):
215
def __init__(self, theme=None, prefix=">>> "):
216
super().__init__(theme)
217
self.prefix = prefix
218
219
def render(self, question, answers=None):
220
# Add custom prefix to all prompts
221
original_message = question.message
222
question._message = f"{self.prefix}{original_message}"
223
224
try:
225
return super().render(question, answers)
226
finally:
227
# Restore original message
228
question._message = original_message
229
230
# Use custom renderer
231
custom_render = CustomRender(prefix="[CUSTOM] ")
232
answer = custom_render.render(
233
inquirer.Text('name', message="Enter name"),
234
{}
235
)
236
```
237
238
### Error Handling in Rendering
239
240
The render system handles various error conditions:
241
242
```python
243
import inquirer
244
from inquirer.errors import ValidationError
245
246
try:
247
questions = [
248
inquirer.Text('email',
249
message="Email address",
250
validate=lambda _, x: '@' in x or ValidationError(x, "Invalid email"))
251
]
252
answers = inquirer.prompt(questions)
253
except KeyboardInterrupt:
254
print("\\nUser cancelled input")
255
except ValidationError as e:
256
print(f"Validation failed: {e.reason}")
257
```