
<div align="center">
  <img src="../assets/typedialog_logo_h_s.svg" alt="TypeDialog Logo" width="600" />
</div>

# TypeDialog Examples

Complete example collection organized by feature category and backend implementation.

## Quick Start

### First Time

Start here: [`01-basic/`](01-basic/)

```bash
# Run a simple form
cargo run --example form

# Or with a specific backend
cargo run -p typedialog-tui --example form_with_autocompletion
```text

## Example Categories

### 1. **Basic Forms** → [`01-basic/`](01-basic/)
Simple form structures for getting started.
- Form fundamentals
- Sections and grouping
- Basic validation
- **Best for:** Learning the syntax, quick prototypes

### 2. **Advanced Features** → [`02-advanced/`](02-advanced/)
Conditional logic, dynamic fields, complex forms.
- Conditional visibility
- Required field rules
- State management
- **Best for:** Complex workflows, conditional UX

### 2.5 **Multiselect Display Modes** → [`02-multiselect-display-modes/`](02-multiselect-display-modes/)
UI patterns for multiselect field visualization.
- **List mode** - Vertical checkbox list (default, best for few options)
- **Grid mode** - Responsive grid with icons (visual, best for 5-15 options)
- **Dropdown mode** - Native select with search (best for 15+ options)
- Selection constraints: `min_selected`, `max_selected`
- Searchable dropdown filtering
- **Best for:** Understanding multiselect UI patterns, choosing the right display mode for your option count

### 3. **Styling & Appearance** → [`03-styling/`](03-styling/)
Custom borders, themes, and visual design.
- Border styles
- Visual hierarchy
- Theme customization
- **Best for:** CLI aesthetics, branded interfaces

### 4. **Backend-Specific** → [`04-backends/`](04-backends/)
Implementation details for each backend.

| Backend | Path | Best For |
|---------|------|----------|
| **CLI** | [`04-backends/cli/`](04-backends/cli/) | Scripting, server tools, pipes |
| **TUI** | [`04-backends/tui/`](04-backends/tui/) | Interactive terminal apps, dashboards |
| **Web** | [`04-backends/web/`](04-backends/web/) | SaaS, public forms, browsers |

**Running forms by backend:**
```bash
# CLI (default)
cargo run --example form

# TUI
cargo run -p typedialog-tui --example form_with_autocompletion

# Web
cargo run -p typedialog-web -- --config form.toml
```text

### 5. **Fragments & Composition** → [`05-fragments/`](05-fragments/)
Reusable components and form composition.
- Fragment templates
- Includes and inheritance
- Component libraries
- **Array management** with RepeatingGroup fields (add/edit/delete)
- **Unique item validation** - prevent duplicate entries in arrays (all backends: CLI, TUI, Web)
- **min/max items constraints** - enforce array size limits
- **Best for:** Large projects, DRY principle, multiple forms, collections with constraints

**Key examples:**
- [`array-trackers.toml`](05-fragments/array-trackers.toml) - UDP/HTTP tracker arrays with `unique = true`
- [`fragments/tracker-udp-item.toml`](05-fragments/fragments/tracker-udp-item.toml) - UDP listener item structure
- [`fragments/tracker-http-item.toml`](05-fragments/fragments/tracker-http-item.toml) - HTTP listener item structure

**Testing RepeatingGroups:**
```bash
# CLI - Interactive menu with add/edit/delete
cargo run --example array_trackers

# TUI - Split-pane interface with keyboard shortcuts
cargo run -p typedialog-tui --example array_trackers

# Web - Inline expandable cards with live counter
cargo run -p typedialog-web -- --config examples/05-fragments/array-trackers.toml
```text

### 6. **Integrations** → [`06-integrations/`](06-integrations/)
External tool integrations.

| Integration | Path |
|-------------|------|
| **Nickel** (Type-safe schemas) | [`06-integrations/nickel/`](06-integrations/nickel/) |

### 6.5 **Multi-Language Support (i18n)** → [`06-i18n/`](06-i18n/)
Translation files and internationalization patterns.
- **TOML translations** - Simple key-value format (en-US.toml, es-ES.toml)
- **Fluent translations** - Advanced format with plurals (*.ftl files)
- Translation organization by form context
- Pre-built translations for common forms
- Comparing TOML vs Fluent translation structures
- **Best for:** Understanding translation file formats, setting up multi-language forms, learning i18n best practices

### 7. **Nickel Schema Generation** → [`07-nickel-generation/`](07-nickel-generation/)
Nickel type-safe schemas with TypeDialog form integration.
- Array(Record) types for collections
- RepeatingGroup field mapping to Nickel arrays
- Complex schema structures
- **Best for:** Type-safe configuration, validation, schema-driven forms

**Key examples:**
- [`arrays-schema.ncl`](07-nickel-generation/arrays-schema.ncl) - Complete schema with Array types
- [`arrays-form.toml`](07-nickel-generation/arrays-form.toml) - Form with RepeatingGroup arrays
- Fragments for: `api-endpoint-item.toml`, `user-item.toml`

### 8. **Encryption & Sensitive Data** → [`08-encryption/`](08-encryption/)
Handling sensitive fields with encryption.
- Field encryption
- Sensitive data redaction
- Encrypted storage
- **Best for:** Security-sensitive forms, PII handling

### 8.5 **Nickel Roundtrip Editing** → [`08-nickel-roundtrip/`](08-nickel-roundtrip/)
Complete workflow for editing type-safe configurations interactively.
- **Load existing config** - Parse Nickel file to JSON
- **Edit via form** - Choose backend (CLI/TUI/Web)
- **Regenerate config** - Render back to Nickel with Tera templates
- **Validate & diff** - Check output and show changes
- Backend comparison for same workflow (CLI vs TUI vs Web)
- Field mapping via `nickel_path` attribute
- Multi-agent coordination for complex configs
- **Best for:** Configuration management, editing existing Nickel configs, understanding form-to-config pipelines

**Running the roundtrip:**
```bash
# CLI: Interactive terminal prompts
./02-roundtrip-cli.sh

# TUI: Full terminal interface
./03-roundtrip-tui.sh

# Web: Browser-based editing
./04-roundtrip-web.sh
```

### 9. **AI Backend** → [`10-ai-backend/`](10-ai-backend/)
RAG system, knowledge graphs, and embeddings.
- RAG (Retrieval-Augmented Generation) system
- Batch document operations
- Semantic + keyword search
- Performance optimization
- **Best for:** ML-powered search, knowledge management, semantic retrieval

**Running AI examples:**
```bash
# Build AI backend
just build::ai

# Run the AI backend example
cargo run --example main --features ai_backend

# Or test AI module
just test::ai
```text

### 10. **Real-World Templates** → [`09-templates/`](09-templates/)
Production-ready examples for common use cases.

| Template | Path | Use Case |
|----------|------|----------|
| **Employee Onboarding** | [`09-templates/employee_onboarding/`](09-templates/employee_onboarding/) | HR systems |
| **User Registration** | [`09-templates/user_registration/`](09-templates/user_registration/) | SaaS, apps |
| **Library Catalog** | [`09-templates/library_catalog/`](09-templates/library_catalog/) | Management systems |

### 11. **Provisioning Generation** → [`11-prov-gen/`](11-prov-gen/)
Infrastructure as Code and configuration generation.
- Infrastructure provisioning
- Configuration management
- Resource templates
- **Best for:** DevOps automation, cloud deployment

### 12. **Agent Execution** → [`12-agent-execution/`](12-agent-execution/)
AI agent execution with multi-provider LLM support.

| Example | LLM Provider | Use Case |
|---------|--------------|----------|
| **Basic Greeting** | Claude Haiku | Simple agent introduction |
| **Code Review** | Claude Sonnet | Security & performance analysis |
| **Documentation** | GPT-4o | Generate docs from code |
| **Task Planner** | Claude Sonnet | Project planning & breakdown |
| **Local Privacy** | Ollama (local) | Privacy-first data analysis |
| **Creative Writer** | Gemini 2.0 | Creative content generation |
| **Refactoring** | GPT-4o-mini | Code refactoring assistant |
| **Architect** | Claude Opus | High-level design & ADRs |

**Features:**
- Template variables & conditionals
- File imports with glob patterns
- Shell command integration
- Output validation
- 4 LLM providers (Claude, OpenAI, Gemini, Ollama)

**Running agent examples:**
```bash
# Run an agent
cargo run --package typedialog-ag -- examples/12-agent-execution/basic-greeting.agent.mdx

# See all examples
cat examples/12-agent-execution/README.md
```text

**Related:**
- [Demos](../demos/agent/) - Multi-provider comparison demos
- [Tests](../tests/agent/) - Agent validation tests
- [Core Examples](../crates/typedialog-agent/typedialog-ag-core/examples/) - Rust API usage

### 13. **Conditional Logic** → [`13-conditional-logic/`](13-conditional-logic/)

Complete guide to all conditional operators and expressions.

**Operators demonstrated:**

| Category | Operators | Example |
|----------|-----------|---------|
| **Comparison** | `==`, `!=`, `>`, `<`, `>=`, `<=` | `port >= 1024` |
| **String** | `contains`, `startswith`, `endswith` | `url startswith https` |
| **Array** | `in` | `rust in detected_languages` |
| **File System** | `file_exists()`, `!file_exists()` | `!file_exists(Dockerfile)` |

**Features:**

- Dynamic field visibility based on user input
- Conditional fragment loading
- Multi-condition scenarios
- Type-safe comparisons

**Running the example:**

```bash
# CLI
cargo run --bin typedialog -- examples/13-conditional-logic/conditional-demo.toml

# TUI
cargo run --bin typedialog-tui -- examples/13-conditional-logic/conditional-demo.toml

# Web
cargo run --bin typedialog-web -- examples/13-conditional-logic/conditional-demo.toml
```text

**Best for:** Dynamic forms, adaptive UX, configuration wizards

### 14. **Validators and Contracts** → [`14-validators-and-contracts/`](14-validators-and-contracts/)

Master validation patterns, constraints, and type-safe contracts.

**Validation levels demonstrated:**

| Level | Mechanism | Examples |
|-------|-----------|----------|
| **Field-Level** | Built-in validators | `required`, `min/max`, date ranges |
| **Array-Level** | Constraints | `min_items`, `max_items`, `unique` |
| **Selection-Level** | Multiselect limits | `min_selected`, `max_selected` |
| **Conditional** | Smart visibility | `when` clause for dependencies |
| **Type-Safe** | Nickel contracts | Compile-time validation |

**Examples included:**

- **Basic Validators** (`basic-validators.toml`) - Required fields, numeric ranges, date validation, multiselect constraints
- **Advanced Validators** (`advanced-validators.toml`) - Smart defaults, field dependencies, uniqueness, regex patterns
- **Conditional Validators** (`conditional-validators.toml`) - Multi-level conditionals, account-type logic, cascading requirements
- **Type-Safe Contracts** (`nickel-validators.ncl`) - Custom validation predicates, strong typing, compile-time checks

**Running examples:**

```bash
# CLI - Interactive prompts with validation
cargo run -p typedialog -- --config examples/14-validators-and-contracts/basic-validators.toml

# TUI - Terminal UI with real-time feedback
cargo run -p typedialog-tui -- examples/14-validators-and-contracts/conditional-validators.toml

# Web - Browser forms with validation
cargo run -p typedialog-web -- --config examples/14-validators-and-contracts/advanced-validators.toml

# Nickel contracts evaluation
nickel eval examples/14-validators-and-contracts/nickel-validators.ncl
```text

**Best for:** Ensuring data quality, enforcing business rules, type-safe schemas

**See also:** [`14-validators-and-contracts/README.md`](14-validators-and-contracts/README.md) for comprehensive guide

### 16. **Agent + Form Integration** → [`16-agent-form-integration/`](16-agent-form-integration/)

Human-in-the-loop AI workflows with forms as validation checkpoints.

**Multi-agent collaboration:**
- Project analyzer (Claude Sonnet) - Initial questionnaire analysis
- Requirements validator (GPT-4o) - Constraint validation
- Recommendations generator (Claude Opus) - Final synthesis and ADRs

**Workflow:**
1. **Form Input** - Collect project requirements via interactive form
2. **Agent Analysis** - AI evaluates against architecture patterns
3. **User Validation** - Review form with agent-suggested changes
4. **Agent Synthesis** - Final recommendations and ADRs
5. **Output** - Markdown with architecture decisions

**Key concepts:**
- Agent responsibilities vs form responsibilities
- Human-in-the-loop decision making
- Multi-agent coordination with forms as gates
- JSON data interchange between agents and forms
- LLM provider diversity (Anthropic, OpenAI)

**Features:**
- 3 agent definitions (.agent.mdx files)
- 3 form definitions (questionnaire, review, feedback)
- Orchestration script (workflow.sh)
- Architecture pattern library
- Validation rules

**Running the workflow:**
```bash
# Execute complete 6-step workflow
./workflow.sh

# Or run individual steps
typedialog form architecture-form.toml
typedialog-ag project-architect-1.agent.mdx
```

**Best for:** Understanding agent + UI integration, building AI-assisted decision systems, multi-agent workflows, human-in-the-loop AI

### 17. **Advanced i18n (Multi-Locale)** → [`17-advanced-i18n/`](17-advanced-i18n/)

Production-grade internationalization with 9+ locales and advanced translation features.

**9 complete locales:**
- English (en-US, en-GB) - Different spelling, currency
- Spanish (es-ES, es-MX) - Gender-aware strings
- Portuguese (pt-BR, pt-PT) - Fallback chains
- French (fr-FR) - Gender-aware, plurals
- Japanese (ja-JP) - No plural rules
- Arabic (ar-SA) - RTL layout, 6 plural forms

**Advanced features:**
- **Fluent format** - Complex pluralization, gender, context
- **Fallback chains** - pt-BR → pt → es → en-US
- **Plural handling** - 2-6 forms per language
- **Gender-aware strings** - Spanish, French articles
- **RTL support** - Arabic layout
- **Formatted output** - Numbers ($1,234.56 vs 1.234,56€), dates, addresses
- **Translation coverage matrix** - Track translation status

**Example use case:** E-commerce checkout form
- Quantities (plural: 1 item, 2-4 items, 5+ items)
- Currency formatting per locale
- Date format localization
- Address format (US vs EU vs Japan)
- Direction handling (LTR vs RTL)

**Features:**
- Fluent syntax with selectors and functions
- Locale priority and fallback strategy
- Number/date formatting per locale
- Missing translation fallback handling
- Translation maintenance workflow
- Programmatic translation testing

**Testing all locales:**
```bash
# Test each locale
./test-locales.sh

# Or test specific locale
LANG=ar-SA cargo run -p typedialog-tui -- checkout-form.toml
```

**Best for:** Building global applications, advanced i18n patterns, pluralization and gender agreement, RTL support, production translation workflows

### 15. **Cross-Backend Same Form** → [`15-cross-backend-same-form/`](15-cross-backend-same-form/)

Demonstrate the power of TypeDialog's multi-backend architecture with one form definition running on three completely different user interfaces.

**Architecture demonstrated:**

One TOML form definition, three backends, identical data output. Only the presentation layer adapts:

| Aspect | CLI | TUI | Web |
|--------|-----|-----|-----|
| **Interface** | Sequential text prompts | Full terminal UI | HTML/CSS forms |
| **Styling** | Emoji + text | Colors, borders, themes | Custom HTML/CSS |
| **Interaction** | Text selection | Keyboard + mouse | Mouse + keyboard |
| **Complexity** | Simple | Rich visual | Browser-based |
| **Data Output** | ✅ Identical | ✅ Identical | ✅ Identical |

**Key learning:**

- Forms are backend-agnostic - define once, deploy anywhere
- Same TOML works on CLI (scripting), TUI (interactive), Web (public)
- Each backend auto-adapts UI components to its strengths
- Output format independent of backend (JSON/YAML/TOML)

**The employee-registration.toml example includes:**

- 6 multi-section form with 25+ fields
- All field types: text, select, multiselect, date, confirm, editor
- Form validation (required, min/max)
- Conditional logic (`when` clause for dependencies)
- Visual comparison mockups for each backend

**Running on each backend:**

```bash
# CLI - Interactive terminal prompts
cargo run -p typedialog -- --config examples/15-cross-backend-same-form/employee-registration.toml

# TUI - Full terminal UI with styling
cargo run -p typedialog-tui -- examples/15-cross-backend-same-form/employee-registration.toml

# Web - Browser-based forms
cargo run -p typedialog-web -- --config examples/15-cross-backend-same-form/employee-registration.toml
# Open http://localhost:3000
```

**Best for:** Understanding multi-backend deployment, choosing the right interface for your use case, building forms that work everywhere, real-world workflows combining multiple backends

**See also:** [`15-cross-backend-same-form/README.md`](15-cross-backend-same-form/README.md) for visual mockups and detailed backend comparison

## Learning Path

```text
START HERE
    ↓
01-basic/ ← Understand form structure
    ↓
02-advanced/ ← Add conditional logic
    ↓
03-styling/ ← Customize appearance
    ↓
04-backends/ ← Choose your backend
    ├→ 04-backends/cli/ ← Scripting
    ├→ 04-backends/tui/ ← Interactive UX
    └→ 04-backends/web/ ← Web deployment
    ↓
05-fragments/ ← Scale to multiple forms
    ├→ array-trackers.toml ← Manage collections with RepeatingGroup
    │
06-integrations/ ← Advanced integrations
    ├→ Nickel schemas
    └→ i18n translations
    ↓
07-nickel-generation/ ← Type-safe schemas with arrays
    ├→ arrays-schema.ncl ← Array(Record) types
    └→ arrays-form.toml ← RepeatingGroup fields
    ↓
08-encryption/ ← Secure sensitive fields
    │
10-ai-backend/ ← Add AI/ML features
    ├→ RAG system for semantic search
    ├→ Batch operations for efficiency
    └→ Knowledge graph integration
    ↓
09-templates/ ← Deploy to production

OPTIONAL ADVANCED TOPICS
    ↓
11-prov-gen/ ← Infrastructure as Code generation
    ↓
13-conditional-logic/ ← Deep dive on all conditional operators
    ↓
14-validators-and-contracts/ ← Master validation & type-safe contracts
    │
15-cross-backend-same-form/ ← Multi-backend architecture & deployment
    │
12-agent-execution/ ← AI agents with multi-provider LLM support
```text

## Common Tasks

### Run a Basic Example
```bash
cargo run --example form
```text

### Try Different Backends
```bash
# CLI
cargo run --example form

# TUI
cargo run -p typedialog-tui --example tui_survey_form

# Web
cargo run -p typedialog-web -- --config examples/04-backends/web/web_registration_form.toml
```text

### Use with TOML Configuration
```bash
cargo run -p typedialog-web -- --config examples/01-basic/form_with_sections.toml
```text

### Use with Rust Code
```bash
cargo run --example form_with_autocompletion
```text

### Test Conditional Logic
```bash
cargo run --example conditional_required_demo
```text

### Try Multi-Language Support
```bash
LANG=es cargo run --example test_i18n_form
```text

### Explore Validation Patterns
```bash
# Learn basic validation
cargo run -p typedialog -- --config examples/14-validators-and-contracts/basic-validators.toml

# Try advanced validators with dependencies
cargo run -p typedialog-tui -- examples/14-validators-and-contracts/advanced-validators.toml

# Master conditional field visibility
cargo run -p typedialog-web -- --config examples/14-validators-and-contracts/conditional-validators.toml
```text

### Work with Type-Safe Contracts
```bash
# Evaluate Nickel schema
nickel eval examples/14-validators-and-contracts/nickel-validators.ncl

# Convert to TOML and use with TypeDialog
nickel query examples/14-validators-and-contracts/nickel-validators.ncl inputs | \
  typedialog parse-nickel > nickel-form.toml
```text

### Compare Multi-Backend Implementations
```bash
# Run the same form on CLI
cargo run -p typedialog -- --config examples/15-cross-backend-same-form/employee-registration.toml

# Run on TUI
cargo run -p typedialog-tui -- examples/15-cross-backend-same-form/employee-registration.toml

# Run on Web
cargo run -p typedialog-web -- --config examples/15-cross-backend-same-form/employee-registration.toml
# Open http://localhost:3000

# Compare: Fill the form identically on all three backends and check output format consistency
```text

## File Types

### TOML (`.toml`)
Configuration-driven forms - fastest iteration.
```bash
cargo run -p typedialog-web -- --config form.toml
```text

### Rust (`.rs`)
Programmatic forms - maximum control.
```bash
cargo run --example form_example
```text

### Nickel (`.ncl`)
Type-safe schema generation.
```bash
nickel eval schema.ncl > form.toml
```text

## Backend Compatibility

| Feature | CLI | TUI | Web |
|---------|-----|-----|-----|
| TOML forms | ✓ | ✓ | ✓ |
| Rust code | ✓ | ✓ | - |
| Conditional fields | ✓ | ✓ | ✓ |
| Autocompletion | ✓ | ✓ | ✓ |
| Custom styling | - | ✓ | ✓ |
| Validation | ✓ | ✓ | ✓ |
| i18n support | ✓ | ✓ | ✓ |
| Fragments | ✓ | ✓ | ✓ |

## Tips

### For CLI Forms
- Use for scripts and automation
- Good for piping between tools
- Minimal dependencies

### For TUI Forms
- Create interactive dashboards
- Better UX than CLI
- Keyboard shortcuts available
- Mouse support

### For Web Forms
- Public-facing forms
- Rich styling options
- Browser validation
- Mobile-friendly
- RESTful API integration

## Troubleshooting

**"Example not found"**
- Check example is in `examples/` directory
- Use `--example` flag with cargo

**"Feature not compiled"**
- Run: `cargo build --all-features`
- Check feature flags in Cargo.toml

**"Form not displaying"**
- For web: Check terminal output for port
- For TUI: Ensure terminal supports the feature
- For CLI: Check input/output redirection

## Next Steps

1. Read the category README for your use case
2. Copy and modify an example form
3. **Add validation:** See [`14-validators-and-contracts/`](14-validators-and-contracts/) for validation patterns
4. Consult [`06-integrations/`](06-integrations/) for advanced features
5. Deploy a template from [`09-templates/`](09-templates/)
6. Integrate with your application

## Contributing Examples

To add new examples:
1. Create in appropriate category
2. Add README explaining the example
3. Include usage instructions
4. List features demonstrated
5. Provide expected output

---

**Start with:** [`01-basic/README.md`](01-basic/README.md)
**Need validation?** See [`14-validators-and-contracts/`](14-validators-and-contracts/)
**Compare backends?** See [`15-cross-backend-same-form/`](15-cross-backend-same-form/)
**Need specific backend?** Check [`04-backends/`](04-backends/)
**Want real-world example?** See [`09-templates/`](09-templates/)
