1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
|
# SelectUI Examples
This directory contains examples demonstrating how to use `selectui` as a library in your Python applications.
## Quick Start
The simplest way to use selectui as a library:
```python
from selectui import SelectUI
items = [
{"title": "Option 1", "subtitle": "Description 1"},
{"title": "Option 2", "subtitle": "Description 2"},
]
app = SelectUI(items=items, oneshot=True)
app.run()
if app.selected_item:
print(f"Selected: {app.selected_item}")
```
## Examples
### minimal.py
The most basic example - select from a list of items and get the result.
```bash
python examples/minimal.py
```
**Features demonstrated:**
- Basic item list with title and subtitle
- Oneshot mode (exits after selection)
- Accessing the selected item via `app.selected_item`
### simple_library_example.py
Interactive menu showing different usage patterns.
```bash
python examples/simple_library_example.py
```
**Features demonstrated:**
- Multiple selection functions
- Custom title/subtitle keys
- File selection from directory
- Using info_key for additional display
### library_usage.py
Comprehensive examples covering all major features.
```bash
# Run a specific example (1-6)
python examples/library_usage.py 1
```
**Features demonstrated:**
1. **Basic selection** - Simple item selection with oneshot mode
2. **Custom keys** - Using custom dictionary keys for title/subtitle/info
3. **Continuous mode** - Multiple selections (oneshot=False)
4. **Events mode** - Handling CTRL+key events
5. **Single-line display** - No subtitle, compact display
6. **Command mode** - Dynamic item generation from shell commands
### pydantic_example.py
Examples using Pydantic models for type safety and validation.
```bash
# Run a specific example (1-5)
python examples/pydantic_example.py 1
```
**Features demonstrated:**
1. **Basic Pydantic models** - Using SelectItem for type-safe items
2. **Pydantic validation** - Automatic validation of item fields
3. **Converting from dicts** - Using SelectItem.from_dict() with custom key mappings
4. **Mixed usage** - Combining Pydantic models and dicts
5. **Custom data field** - Storing additional data with items
### json_conversion.py
Examples showing JSON-to-SelectItem conversion with custom key mappings.
```bash
# Run a specific example (1-4)
python examples/json_conversion.py 1
```
**Features demonstrated:**
1. **Custom product JSON** - Converting product data with non-standard keys
2. **GitHub-style API** - Handling GitHub API response format
3. **Generic API response** - Working with nested API responses
4. **No subtitle (single-line)** - Single-line display from JSON
### test_pydantic.py
Integration tests for Pydantic SelectItem functionality.
```bash
python examples/test_pydantic.py
```
**Tests included:**
- SelectItem creation and validation
- Dictionary conversion with custom keys
- SelectUI integration with Pydantic models
## Pydantic Models (New!)
SelectUI now supports Pydantic models for type safety and validation.
### Using SelectItem
```python
from selectui import SelectUI, SelectItem
# Create type-safe items
items = [
SelectItem(
title="Python",
subtitle="Programming language",
info="1991",
data={"website": "python.org"}
),
SelectItem(
title="Rust",
subtitle="Systems language",
info="2010",
data={"website": "rust-lang.org"}
),
]
app = SelectUI(items=items, oneshot=True)
app.run()
```
### Converting from JSON/Dicts
```python
from selectui import SelectItem
# Custom key mappings
data = {"name": "Alice", "role": "Engineer", "team": "Backend"}
item = SelectItem.from_dict(
data,
title_key="name",
subtitle_key="role",
info_key="team"
)
# item.title == "Alice"
# item.subtitle == "Engineer"
# item.info == "Backend"
# item.data contains all original fields
```
### Benefits
- **Type Safety**: Catch errors at development time
- **Validation**: Automatic validation of required fields
- **IDE Support**: Better autocomplete and type hints
- **Flexibility**: Mix Pydantic models and dicts seamlessly
## Key Parameters
### SelectUI Constructor
```python
SelectUI(
items=[], # List of dict items to display
oneshot=False, # Exit after first selection?
title_key="title", # Dict key for item title
subtitle_key=None, # Dict key for subtitle (None = single line)
info_key=None, # Dict key for right-aligned info
events_mode=False, # Emit CTRL+key events?
command_template=None, # Command template for dynamic items
)
```
### Return Value
After calling `app.run()`, access the selected item:
```python
app.selected_item # The selected dict item, or None
```
## Common Patterns
### Simple Selection
```python
app = SelectUI(items=my_items, oneshot=True)
app.run()
return app.selected_item
```
### Custom Display Keys
```python
items = [
{"name": "Alice", "job": "Engineer", "dept": "Backend"},
{"name": "Bob", "job": "Designer", "dept": "Product"},
]
app = SelectUI(
items=items,
title_key="name",
subtitle_key="job",
info_key="dept",
oneshot=True
)
```
### Single-Line Display
```python
app = SelectUI(
items=items,
title_key="filename",
subtitle_key=None, # No subtitle
oneshot=True
)
```
### Continuous Selection
```python
app = SelectUI(items=items, oneshot=False)
app.run()
# User can select multiple items, app stays open until quit
```
### Events Mode
```python
app = SelectUI(items=items, events_mode=True, oneshot=False)
app.run()
# CTRL+key combinations emit events to stdout
```
## Integration Tips
### In a CLI Tool
```python
def select_config_file():
"""Let user select a config file."""
import glob
files = [{"title": f} for f in glob.glob("*.conf")]
if not files:
print("No config files found")
return None
app = SelectUI(items=files, oneshot=True)
app.run()
return app.selected_item
```
### In a TUI Application
```python
def get_user_choice(options):
"""Generic selection function."""
items = [{"title": opt} for opt in options]
app = SelectUI(items=items, oneshot=True)
app.run()
return app.selected_item.get("title") if app.selected_item else None
```
### With External Data
```python
import json
def select_from_api_results(api_data):
"""Select from API response."""
items = [
{
"title": item["name"],
"subtitle": item["description"],
"id": item["id"]
}
for item in api_data
]
app = SelectUI(
items=items,
title_key="title",
subtitle_key="subtitle",
oneshot=True
)
app.run()
return app.selected_item
```
## Requirements
Make sure selectui is installed or the module is in your Python path:
```bash
# Install in development mode
pip install -e .
# Or add to path in your script
import sys
sys.path.insert(0, 'path/to/selectui/src')
```
|