# Enhanced Input Plugin Specification

## Overview

The Enhanced Input Plugin provides bordered input boxes using Unicode box-drawing characters. Built with modular components following DRY principles, offering 14 different box styles and extensive customization.

**Location:** `plugins/enhanced_input_plugin.py`, `plugins/enhanced_input/`

**Version:** 1.0.0

## Features

### Modular Architecture

- **Component-based design**: Separate modules for config, state, styles, colors, geometry, text processing, cursor management, and rendering
- **DRY principles**: Shared utilities across components
- **Extensible**: Easy to add new box styles

### Box Styles

14 built-in box styles using Unicode box-drawing characters:

| Style | Description |
|-------|-------------|
| `rounded` | Rounded corners (default) |
| `square` | Sharp square corners |
| `double` | Double-line borders |
| `thick` | Thick single-line borders |
| `thin` | Thin single-line borders |
| `dotted` | Dotted border pattern |
| `dashed` | Dashed border pattern |
| `minimal` | Minimal border (corners only) |
| `brackets` | Bracket-style corners `[ ]` |
| `underline` | Underline only (bottom border) |
| `lines_only` | Horizontal lines only |
| `dots_only` | Vertical dots only |
| `mixed_weight` | Mixed thick/thin borders |
| `sophisticated` | Complex decorative border |

### Customization Options

- **Width control**: Auto, fixed pixels, or percentage
- **Placeholder text**: Customizable input placeholder
- **Corner style**: Per-style border characters
- **Color scheme**: Configurable colors for different parts
- **Animation support**: Optional border animations

## Architecture

### Plugin Structure

```
plugins/enhanced_input/
├── __init__.py
├── config.py               # InputConfig class with default settings
├── state.py                # PluginState for tracking render state
├── box_styles.py           # BoxStyleRegistry with 14+ styles
├── color_engine.py         # ColorEngine for color management
├── geometry.py             # GeometryCalculator for layout
├── text_processor.py       # TextProcessor for text manipulation
├── cursor_manager.py       # CursorManager for cursor position
├── box_renderer.py         # BoxRenderer for final rendering
└── enhanced_input_plugin.py # Main plugin class
```

### Main Plugin Class

```python
class EnhancedInputPlugin:
    - get_default_config() -> Dict[str, Any]
    - get_startup_info(config) -> List[str]
    - get_config_widgets() -> Dict[str, Any]
    - initialize(event_bus, config, **kwargs) -> None
    - shutdown() -> None
    - register_hooks() -> None
    - render_input_box(prompt: str, input_text: str, cursor_pos: int) -> str
```

### Component Classes

```python
class InputConfig:
    - get_default_config_dict() -> Dict[str, Any]

class PluginState:
    - should_redraw() -> bool
    - mark_dirty() -> None

class BoxStyleRegistry:
    - get_style(style_name: str) -> Dict[str, str]

class ColorEngine:
    - apply_color(text: str, color: str) -> str
    - reset_color() -> str

class GeometryCalculator:
    - calculate_box_width(text: str, width: str, term_width: int) -> int
    - calculate_inner_width(box_width: int, style: Dict) -> int

class TextProcessor:
    - wrap_text(text: str, width: int) -> List[str]
    - truncate_text(text: str, max_length: int) -> str

class CursorManager:
    - calculate_cursor_row_col(text: str, cursor_pos: int, width: int) -> Tuple[int, int]

class BoxRenderer:
    - render_box(prompt: str, input_text: str, cursor_pos: int, config, state) -> str
```

## Configuration

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `enabled` | boolean | `true` | Enable the plugin |
| `style` | string | `"rounded"` | Box style name |
| `width` | string | `"auto"` | Box width (auto, pixels, or percentage) |
| `placeholder_text` | string | `"Type a message..."` | Input placeholder |
| `show_border` | boolean | `true` | Show box border |
| `animate_border` | boolean | `false` | Enable border animation |
| `border_color` | string | `"cyan"` | Border color |
| `prompt_color` | string | `"lime"` | Prompt color |
| `text_color` | string | `"white"` | Input text color |

### Configuration File

Edit `~/.kollabor-cli/config.json`:

```json
{
  "plugins": {
    "enhanced_input": {
      "enabled": true,
      "style": "rounded",
      "width": "auto",
      "placeholder_text": "Type a message...",
      "show_border": true,
      "animate_border": false,
      "border_color": "cyan",
      "prompt_color": "lime",
      "text_color": "white"
    }
  }
}
```

### Configuration Widgets

The plugin provides UI widgets for interactive configuration:

```python
{
  "title": "Enhanced Input Plugin",
  "widgets": [
    {
      "type": "dropdown",
      "label": "Box Style",
      "config_path": "plugins.enhanced_input.style",
      "options": [
        "rounded", "square", "double", "thick", "thin",
        "dotted", "dashed", "minimal", "brackets", "underline",
        "lines_only", "dots_only", "mixed_weight", "sophisticated"
      ]
    },
    {
      "type": "text_input",
      "label": "Width",
      "config_path": "plugins.enhanced_input.width",
      "placeholder": "auto"
    },
    {
      "type": "text_input",
      "label": "Placeholder Text",
      "config_path": "plugins.enhanced_input.placeholder_text",
      "placeholder": "Type a message..."
    },
    {
      "type": "checkbox",
      "label": "Show Border",
      "config_path": "plugins.enhanced_input.show_border"
    },
    {
      "type": "checkbox",
      "label": "Animate Border",
      "config_path": "plugins.enhanced_input.animate_border"
    }
  ]
}
```

## Box Style Definitions

### Rounded Style (Default)

```
╭─────────────────────────────╮
│ prompt ▶                   │
│ Input text here...          │
╰─────────────────────────────╯
```

### Square Style

```
┌─────────────────────────────┐
│ prompt ▶                   │
│ Input text here...          │
└─────────────────────────────┘
```

### Double Style

```
╔═════════════════════════════╗
║ prompt ▶                   ║
║ Input text here...          ║
╚═════════════════════════════╝
```

### Minimal Style

```
prompt ▶ Input text here...
```

### Underline Style

```
prompt ▶ Input text here...
───────────────────────────────
```

## Render Pipeline

1. **Config Loading**: Load plugin configuration
2. **State Check**: Determine if redraw needed
3. **Geometry Calculation**: Calculate box dimensions
4. **Text Processing**: Wrap and truncate text
5. **Cursor Calculation**: Determine cursor position
6. **Style Application**: Apply box style and colors
7. **Final Rendering**: Generate final output string

## Display Example

```python
render_input_box("You", "Hello world!", 12)
```

Output (rounded style, cyan border):

```
╭────────────────────────────────────╮
│ You ▶ Hello world!              │
╰────────────────────────────────────╯
```

## Implementation Checklist

### Core Functionality
- [x] Modular component architecture
- [x] 14+ box styles
- [x] Geometry calculation
- [x] Text wrapping and truncation
- [x] Cursor position management
- [x] Color engine integration

### Advanced Features
- [x] Auto width calculation
- [x] Placeholder text support
- [x] Border animation (configurable)
- [x] Configuration widgets
- [x] State-based redraw optimization
- [x] Unicode box-drawing characters

### Configuration
- [x] Style selection
- [x] Width control (auto/pixels/percentage)
- [x] Placeholder customization
- [x] Color scheme configuration
- [x] Border visibility toggle

### Testing
- [ ] Unit tests for each component
- [ ] Integration tests for rendering
- [ ] Cross-platform terminal testing

## Color Engine

### Supported Colors

Standard terminal colors:
- black, red, green, yellow, blue, magenta, cyan, white
- bright_black, bright_red, bright_green, bright_yellow, bright_blue, bright_magenta, bright_cyan, bright_white

Extended colors (256-color mode):
- RGB values: `rgb(123, 45, 67)`
- Color codes: `color(42)`

### Color Application

```python
ColorEngine.apply_color("text", "cyan")  # Cyan text
ColorEngine.apply_color("text", "rgb(0, 255, 0)")  # Custom green
ColorEngine.reset_color()  # Reset to default
```

## Performance Considerations

### Redraw Optimization

- **State tracking**: `PluginState` tracks last render state
- **Dirty flag**: Only redraw when content changes
- **Minimal calculations**: Skip unnecessary geometry calculations

### Unicode Handling

- **Pre-compiled characters**: Box characters stored as constants
- **Cached styles**: Style definitions cached after first use
- **Efficient string building**: List comprehension for output

## Error Handling

### Common Errors

| Error | Cause | Resolution |
|-------|-------|------------|
| Invalid style name | Style not in registry | Check available styles |
| Width calculation error | Invalid width string | Use "auto", "80", or "80%" |
| Terminal width unavailable | Can't get terminal size | Fallback to 80 columns |
| Unicode display issues | Terminal doesn't support Unicode | Use square or minimal style |

## Related Documentation

- /docs/reference/unicode-box-drawing.md - Unicode box characters reference
- /docs/plugins/core/background_tasks_plugin_spec.md - Background tasks (similar modular design)
- /docs/architecture/component-based-plugins.md - Component-based plugin architecture

## Design Patterns

### Separation of Concerns

Each component has a single responsibility:
- `Config`: Configuration management
- `State`: Render state tracking
- `BoxStyleRegistry`: Style definitions
- `ColorEngine`: Color management
- `GeometryCalculator`: Layout calculations
- `TextProcessor`: Text manipulation
- `CursorManager`: Cursor positioning
- `BoxRenderer`: Final output generation

### Dependency Injection

Components receive dependencies via constructor:
- `BoxRenderer` takes config, state, style registry, color engine, geometry, text processor, cursor manager

### Strategy Pattern

Box styles use strategy pattern:
- `BoxStyleRegistry` returns style-specific border characters
- New styles can be added without modifying core logic

## Extension Points

### Adding New Box Styles

1. Add style definition to `BoxStyleRegistry.STYLES`:

```python
STYLES["custom"] = {
    "top_left": "┌",
    "top_right": "┐",
    "bottom_left": "└",
    "bottom_right": "┘",
    "horizontal": "─",
    "vertical": "│",
    "top_tee": "┬",
    "bottom_tee": "┴",
    "left_tee": "├",
    "right_tee": "┤",
    "cross": "┼"
}
```

2. Add to widget options list

3. Restart to use new style

### Custom Color Schemes

Implement custom color engine:

```python
class CustomColorEngine(ColorEngine):
    def apply_color(self, text: str, color: str) -> str:
        # Custom color logic
        pass
```

## Usage Example

```python
from plugins.enhanced_input_plugin import EnhancedInputPlugin

# Create plugin instance
plugin = EnhancedInputPlugin()

# Initialize
await plugin.initialize(event_bus, config, renderer=renderer)

# Render input box
output = plugin.render_input_box(
    prompt="You",
    input_text="Hello world!",
    cursor_pos=12
)

print(output)
# Output:
# ╭────────────────────────────────────╮
# │ You ▶ Hello world!              │
# ╰────────────────────────────────────╯
```
