aboutsummaryrefslogtreecommitdiffstats

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:

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.

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.

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.

# 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.

# 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.

# 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.

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

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

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

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:

app.selected_item  # The selected dict item, or None

Common Patterns

Simple Selection

app = SelectUI(items=my_items, oneshot=True)
app.run()
return app.selected_item

Custom Display Keys

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

app = SelectUI(
    items=items,
    title_key="filename",
    subtitle_key=None,  # No subtitle
    oneshot=True
)

Continuous Selection

app = SelectUI(items=items, oneshot=False)
app.run()
# User can select multiple items, app stays open until quit

Events Mode

app = SelectUI(items=items, events_mode=True, oneshot=False)
app.run()
# CTRL+key combinations emit events to stdout

Integration Tips

In a CLI Tool

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

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

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:

# Install in development mode
pip install -e .

# Or add to path in your script
import sys
sys.path.insert(0, 'path/to/selectui/src')