# Cross-Backend Same Form Example

**Demonstrates the power of TypeDialog's multi-backend architecture:**

One form definition (TOML), three completely different user interfaces.

## Overview

The `employee-registration.toml` form is run identically on **CLI**, **TUI**, and **Web** backends. Only the presentation layer changes based on the backend's capabilities.

This example teaches you:

- ✅ Why TypeDialog's multi-backend approach is powerful
- ✅ How the same form adapts to different interfaces
- ✅ Backend strengths and weaknesses
- ✅ When to choose each backend
- ✅ How to organize forms for portability

---

## The Employee Registration Form

A realistic, multi-section onboarding form featuring

- 6 sections with 25+ fields
- Multiple field types: text, select, multiselect, date, confirm, editor
- Form validation (required, min/max)
- Conditional logic (`when` clause)
- Advanced features (smart defaults, field dependencies)

---

## Running the Same Form

### CLI Backend - Interactive Terminal Prompts

```bash
cargo run -p typedialog -- --config employee-registration.toml
```

**Visual Appearance:**

```text
Employee Registration
━━━━━━━━━━━━━━━━━━━━━━

▶ Personal Information
  First name: █ John
  Last name: █ Doe
  Work email: █ john.doe@company.com
  Phone number: █
  Start date: █ 2025-01-15

▶ Employment Details
  Department:
    (1) 🔧 Engineering
    (2) 📦 Product
    (3) 🎨 Design
  ? █

  Job title: █ Senior Engineer
  ...
```

**Output (JSON):**

```json
{
  "first_name": "John",
  "last_name": "Doe",
  "email": "john.doe@company.com",
  "phone": "+1 (555) 123-4567",
  "start_date": "2025-01-20",
  "department": "engineering",
  "job_title": "Senior Engineer",
  "employment_type": "full_time",
  "manager": "Jane Smith",
  "office_location": "remote",
  "primary_skills": ["rust", "backend", "devops"],
  "years_experience": "8",
  "health_insurance": "premium",
  "work_schedule": "flexible",
  "equipment_needs": ["laptop", "monitor", "keyboard"],
  "enable_2fa": true,
  "2fa_method": "authenticator",
  "vpn_required": false,
  "agreed_policies": true,
  "privacy_consent": true,
  "emergency_contact": "Jane Doe",
  "emergency_phone": "+1 (555) 987-6543",
  "additional_notes": "Prefers standing desk setup"
}
```

**Best for**

- Scripting and automation
- CI/CD pipelines
- Piping between tools
- Server-side form processing
- Headless environments

**Strengths**

- ✅ Zero dependencies beyond Rust
- ✅ Works over SSH
- ✅ Perfect for piping/automation
- ✅ Minimal resource usage
- ✅ Scriptable and testable

**Limitations**

- ❌ No visual styling
- ❌ No mouse support
- ❌ Limited to text-based interface
- ❌ Single column layout only

---

### TUI Backend - Full Terminal UI

```bash
cargo run -p typedialog-tui -- employee-registration.toml
```

**Visual Appearance:**

```text
┌──────────────────────────────────────────────────────────────┐
│ Employee Registration                                        │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  PERSONAL INFORMATION                                        │
│  ─────────────────────────────────────────────────────────  │
│  First name            │ John                              │
│  Last name             │ Doe                               │
│  Work email            │ john.doe@company.com              │
│  Phone number          │ +1 (555) 123-4567                │
│  Start date            │ 2025-01-20                        │
│                                                              │
│  [Tab] Next  [Shift+Tab] Prev  [Enter] Select  [Esc] Exit   │
└──────────────────────────────────────────────────────────────┘
```

**Multiselect Display (Grid Mode):**

```text
┌──────────────────────────────────────────────────────────────┐
│ Primary skills (select 2-5)                                  │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  ☑ 🦀 Rust          ☐ 🐍 Python       ☐ 🐹 Go            │
│  ☑ 🔧 Backend       ☑ 🚀 DevOps       ☐ ☕ Java          │
│  ☐ 📘 TypeScript    ☐ 🎨 Frontend     ☐ ⚙️ C++           │
│  ☐ 🗄️ Database                                              │
│                                                              │
│  [↑/↓] Navigate  [Space] Toggle  [Enter] Confirm            │
└──────────────────────────────────────────────────────────────┘
```

**Date Picker:**

```text
┌──────────────────────────────────────────────────────────────┐
│ Start date                                                   │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│        January 2025                                          │
│   Mo Tu We Th Fr Sa Su                                       │
│            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                                             │
│                                                              │
│  [←/→] Month  [↑/↓] Year  [Enter] Select                    │
└──────────────────────────────────────────────────────────────┘
```

**Best for**

- Interactive system administration tools
- Complex data entry workflows
- Terminal-based dashboards
- Internal tools and CLIs
- Server management

**Strengths**

- ✅ Rich terminal UI with borders, colors, styling
- ✅ Full keyboard navigation (Vi-like keybindings)
- ✅ Mouse support for clicks
- ✅ Multi-pane layouts for complex forms
- ✅ Real-time validation feedback
- ✅ Custom themes and styling
- ✅ Visual progress indication

**Limitations**

- ❌ Terminal must support advanced features
- ❌ Requires proper terminal configuration
- ❌ Limited screen resolution on small terminals
- ❌ Not accessible on all terminals (Windows legacy console)

---

### Web Backend - Browser-Based Forms

```bash
cargo run -p typedialog-web -- --config employee-registration.toml
# Open http://localhost:3000
```

**Visual Appearance (Responsive HTML):**

```html
┌────────────────────────────────────────────────────────────────┐
│ TypeDialog        [≡] Menu                         ? About [×] │
├────────────────────────────────────────────────────────────────┤
│                                                                │
│  Employee Registration                                         │
│                                                                │
│  Personal Information                                          │
│  ──────────────────────────────────────────────────────        │
│                                                                │
│  First name *                                                  │
│  [________________________]  John                               │
│                                                                │
│  Last name *                                                   │
│  [________________________]  Doe                                │
│                                                                │
│  Work email *                                                  │
│  [________________________]  john.doe@company.com              │
│                                                                │
│  Start date *                                                  │
│  [📅 2025-01-20]  ↑↓                                            │
│                                                                │
│  ┌─────────────────────────────────────────────────────────┐  │
│  │ Employment Details                                      │  │
│  │ ──────────────────────────────────────────────────      │  │
│  │                                                         │  │
│  │ Department *                                           │  │
│  │ [▼ 🔧 Engineering                              ]      │  │
│  │                                                         │  │
│  │ Job title *                                            │  │
│  │ [________________________]  Senior Engineer            │  │
│  └─────────────────────────────────────────────────────────┘  │
│                                                                │
│  Skills & Expertise                                            │
│  ──────────────────────────────────────────────────────        │
│                                                                │
│  Primary skills (select 2-5) *                                │
│  ☑ 🦀 Rust      ☑ 🔧 Backend    ☑ 🚀 DevOps              │
│  ☐ 📘 TypeScript  ☐ 🐍 Python    ☐ 🎨 Frontend            │
│  ☐ 🗄️ Database   ☐ ☕ Java      ☐ ⚙️ C++                 │
│                                                                │
│  [Continue ▶]  [◀ Previous]  [Cancel]                         │
└────────────────────────────────────────────────────────────────┘
```

**Mobile View (Responsive):**

```text
┌─────────────────────┐
│ Employee Registration
├─────────────────────┤
│                    │
│ First name *       │
│ [__________]      │
│                    │
│ Last name *        │
│ [__________]      │
│                    │
│ Work email *       │
│ [__________]      │
│                    │
│ [ Continue ▶ ]    │
└─────────────────────┘
```

**Best for**

- Public-facing forms
- SaaS platforms
- Mobile-friendly applications
- Rich UI/UX experiences
- Cloud deployment
- User registration, surveys, data collection

**Strengths**

- ✅ Full HTML/CSS styling and customization
- ✅ Responsive design (mobile-friendly)
- ✅ JavaScript validation on client-side
- ✅ Browser inspection tools
- ✅ Accessibility features (ARIA)
- ✅ Works on any device with a browser
- ✅ Progressive enhancement

**Limitations**

- ❌ Requires running server
- ❌ Slower than CLI/TUI (network overhead)
- ❌ More complex deployment
- ❌ Browser dependencies

---

## Backend Feature Comparison

| Feature | CLI | TUI | Web |
|---------|-----|-----|-----|
| **Basic Fields** | ✅ | ✅ | ✅ |
| **Validation** | ✅ | ✅ | ✅ |
| **Conditional Logic** | ✅ | ✅ | ✅ |
| **Multiselect** | ✅ | ✅ | ✅ |
| **Date Picker** | 📝 | ✅ | ✅ |
| **Editor Field** | 📝 | ✅ | ✅ |
| **Styling** | ❌ | ✅ | ✅ |
| **Mouse Support** | ❌ | ✅ | ✅ |
| **Custom Themes** | ❌ | ✅ | ✅ |
| **Mobile Responsive** | ❌ | ❌ | ✅ |
| **Multi-Page** | 📝 | ✅ | ✅ |
| **Progress Bar** | ❌ | ✅ | ✅ |

Legend: ✅ Full support | 📝 Basic support | ❌ Not supported

---

## Output Format Comparison

All backends produce the same output structure

### JSON (Default)

```bash
cargo run -p typedialog -- --config employee-registration.toml --format json
```

### YAML

```bash
cargo run -p typedialog -- --config employee-registration.toml --format yaml
```

### TOML

```bash
cargo run -p typedialog -- --config employee-registration.toml --format toml
```

**All three backends output identical data** regardless of interface differences.

---

## Choosing the Right Backend

### Use CLI When

- 🔧 Building automation scripts
- 🚀 Deploying in CI/CD pipelines
- 🔌 Piping data between tools
- 🖥️ Working on servers without X11/terminal
- 📊 Building command-line utilities
- 💾 Minimizing resource usage
- 🔐 Working over SSH

### Use TUI When

- 💼 Building internal tools
- 📋 Creating admin dashboards
- 🎮 Interactive system management
- 🖱️ Users prefer keyboard navigation
- 🎨 Terminal styling is desired
- 📱 Complex multi-pane layouts needed
- 🏢 Running on Linux servers with terminal access

### Use Web When

- 🌐 Public-facing applications
- 📱 Mobile access required
- 💻 Rich UI/UX experience needed
- 🎨 Custom branding important
- ♿ Accessibility (WCAG) required
- 📊 Complex visual presentation
- 🚀 Cloud-native deployment
- 👥 Non-technical users

---

## Real-World Workflow

The true power emerges in workflows that combine backends:

```mermaid
graph LR
    A["Web Interface<br/>(User Entry)"] -->|JSON| B["API Server<br/>(Process)"]
    B -->|Validation| C["CLI Tool<br/>(Automation)"]
    C -->|Data| D["Database<br/>(Storage)"]

    E["TUI Admin<br/>(Review)"] -.->|Query| D
    E -->|Export| F["CSV/JSON<br/>(Reporting)"]
```

**Example Flow**

1. **Web Backend** - Collect employee registration from HR admin
2. **API Server** - Validate and process using TypeDialog validation
3. **CLI Tool** - Automate account provisioning scripts
4. **TUI Dashboard** - Admin reviews and manages employees
5. **Database** - Store employee records

---

## Running All Backends Simultaneously

**Terminal 1 - CLI**

```bash
cargo run -p typedialog -- --config employee-registration.toml
```

**Terminal 2 - TUI**

```bash
cargo run -p typedialog-tui -- employee-registration.toml
```

**Terminal 3 - Web**

```bash
cargo run -p typedialog-web -- --config employee-registration.toml
# Open http://localhost:3000
```

**Try filling out the same form on all three backends and compare**

- Visual presentation differences
- Navigation methods
- Data entry experience
- Output consistency

---

## Learning Points

### 1. Form Definition is Backend-Agnostic

The TOML is pure data - no backend-specific code

```toml
[[sections]]
title = "Personal Information"

[[sections.elements]]
name = "first_name"
type = "text"
required = true
```

Works identically on CLI, TUI, Web.

### 2. Each Backend Adapts to Its Strengths

- **CLI**: Sequential prompts, best for automation
- **TUI**: Visual interface, best for interactive use
- **Web**: Rich HTML, best for public/mobile

### 3. Output is Consistent

Whether the user enters data via CLI, TUI, or Web, the JSON/YAML/TOML output is identical.

### 4. One Codebase, Multiple Deployments

- Small deployments? Use CLI
- Internal tools? Use TUI
- Public apps? Use Web

No code changes needed - just redeploy the same form.

---

## Best Practices

### 1. Design Forms for All Backends

Assume your form might be used on any backend

- Keep section titles concise
- Use short field prompts
- Avoid overly complex layouts
- Test on all three backends

### 2. Use Output Validation

Since backends are interchangeable, validate output format:

```bash
# Capture output and validate it
cargo run -p typedialog -- --config employee-registration.toml \
  --format json > employee.json

# Validate with jq
jq . employee.json  # Parses successfully
```

### 3. Combine Backends Strategically

```bash
# Collect data via Web, process with CLI automation
curl http://localhost:3000/submit | \
  cargo run -p typedialog -- --process - --format yaml
```

---

## Advanced: Custom Backend Behavior

While the form is the same, you can configure backend-specific behavior:

```toml
# Default for all backends
[[elements]]
name = "date_field"
type = "date"

# Both TUI and Web will use their native date picker
# CLI will use text input
```

Each backend automatically uses its best-suited UI component.

---

## Troubleshooting

### "Form looks different on TUI"

✅ This is expected! TUI has different layout capabilities

- Wider terminals show more content
- Colors and styling enhance readability
- This is a feature, not a bug

### "CLI doesn't support multiselect selection mode"

✅ Correct - CLI uses text-based selection

```bash
Department:
  (1) 🔧 Engineering
  (2) 📦 Product
  (3) 🎨 Design
? █
```

Just enter the number.

### "Web form submission times out"

Check that web server is running

```bash
cargo run -p typedialog-web -- --config employee-registration.toml
```

Server must be started before opening browser.

---

## Related Examples

- [`04-backends/`](../04-backends/) - Backend-specific features
- [`02-advanced/`](../02-advanced/) - Conditional logic for all backends
- [`05-fragments/`](../05-fragments/) - Reusable form components
- [`14-validators-and-contracts/`](../14-validators-and-contracts/) - Validation across backends

---

## Next Steps

1. **Try all three** - Run the form on each backend
2. **Modify the form** - Add/remove fields and see how each backend adapts
3. **Compare output** - Verify all backends produce identical JSON
4. **Build workflows** - Combine backends in a real scenario
5. **Deploy strategically** - Choose the right backend for your use case

---

**Key Takeaway:** TypeDialog's multi-backend architecture means you write the form once and deploy anywhere. No code changes needed - just choose the interface that fits your use case.
