Skip to main content

Basic Usage Examples

This page contains practical examples of creating TUI applications with Ziva. All examples are ready to run and demonstrate the main features of the library.

Example 1: Simple Confirmation

Basic example with a confirmation task:
package main

import (
    "fmt"
    "log"
    "github.com/qzeleza/ziva"
)

func main() {
    // Create confirmation task
    confirm := ziva.NewYesNoTask(
        "Action Confirmation",
        "Delete all temporary files?",
    )

    // Create queue and add task
    queue := ziva.NewQueue("System Cleanup")
    queue.AddTasks(confirm)

    // Run
    if err := queue.Run(); err != nil {
        log.Fatal(err)
    }

    // Handle result
    if confirm.IsYes() {
        fmt.Println("🗑️  Temporary files deleted")
    } else {
        fmt.Println("❌ Operation canceled")
    }
}

Example 2: List Selection

Example with single option selection from a list:
package main

import (
    "fmt"
    "log"
    "github.com/qzeleza/ziva"
)

func main() {
    // Options with descriptions
    environments := []string{
        "dev||Development environment - local machine",
        "staging||Testing environment - for QA",
        "production||Production environment - live users",
    }

    // Create selection task
    envTask := ziva.NewSingleSelectTask(
        "Deployment Environment Selection",
        environments,
    ).WithDefaultItem("staging")

    // Configure and run queue
    queue := ziva.NewQueue("Application Deployment")
    queue.WithAppName("DeployTool")
    queue.AddTasks(envTask)

    if err := queue.Run(); err != nil {
        log.Fatal(err)
    }

    // Get result
    selected := envTask.GetSelected()
    fmt.Printf("🚀 Deploying to environment: %s\n", selected)
}

Example 3: Multiple Selection

Example with selecting multiple components:
package main

import (
    "fmt"
    "log"
    "strings"
    "github.com/qzeleza/ziva"
)

func main() {
    // Components to install
    components := []string{
        "web||Web server",
        "api||REST API",
        "db||Database",
        "cache||Caching",
        "monitoring||Monitoring",
        "backup||Backup",
    }

    // Create multi-selection task
    compTask := ziva.NewMultiSelectTask(
        "Select components to install",
        components,
    ).WithSelectAll("Install all").
      WithDefaultItems([]string{"web", "api"})

    queue := ziva.NewQueue("System Installation")
    queue.AddTasks(compTask)

    if err := queue.Run(); err != nil {
        log.Fatal(err)
    }

    // Show selected components
    selected := compTask.GetSelected()
    if len(selected) > 0 {
        fmt.Printf("📦 Will install: %s\n",
            strings.Join(selected, ", "))
    } else {
        fmt.Println("❌ No components selected")
    }
}

Example 4: Input with Validation

Example of collecting user data with validation:
package main

import (
    "fmt"
    "log"
    "github.com/qzeleza/ziva"
)

func main() {
    v := ziva.DefaultValidators

    // Create input fields with validation
    name := ziva.NewInputTask("Name", "Enter your name:").
        WithValidator(v.Required())

    email := ziva.NewInputTask("Email", "Enter email:").
        WithInputType(ziva.InputTypeEmail).
        WithValidator(v.Email())

    website := ziva.NewInputTask("Website", "Website URL (optional):").
        WithValidator(v.OptionalURL())

    // Create queue
    queue := ziva.NewQueue("User Registration")
    queue.WithAppName("UserReg")
    queue.AddTasks(name, email, website)

    if err := queue.Run(); err != nil {
        log.Fatal(err)
    }

    // Show collected information
    fmt.Println("\n✅ Registration completed:")
    fmt.Printf("Name: %s\n", name.GetValue())
    fmt.Printf("Email: %s\n", email.GetValue())
    if website.GetValue() != "" {
        fmt.Printf("Website: %s\n", website.GetValue())
    }
}

Example 5: Function Task

Example of executing a long-running operation:
package main

import (
    "log"
    "math/rand"
    "time"
    "github.com/qzeleza/ziva"
)

func main() {
    // Report data
    var stats struct {
        FilesProcessed int
        Errors         int
        Duration       time.Duration
    }

    // Create functional task
    processTask := ziva.NewFuncTask(
        "File Processing",
        func() error {
            start := time.Now()

            // File processing simulation
            for i := 0; i < 100; i++ {
                time.Sleep(50 * time.Millisecond)
                stats.FilesProcessed++

                // Random errors
                if rand.Intn(20) == 0 {
                    stats.Errors++
                }
            }

            stats.Duration = time.Since(start)
            return nil
        },
        // Results summary function
        ziva.WithSummaryFunction(func() []string {
            return []string{
                fmt.Sprintf("Files processed: %d", stats.FilesProcessed),
                fmt.Sprintf("Errors: %d", stats.Errors),
                fmt.Sprintf("Duration: %v", stats.Duration.Round(time.Millisecond)),
            }
        }),
    )

    queue := ziva.NewQueue("Batch Processing")
    queue.AddTasks(processTask)

    if err := queue.Run(); err != nil {
        log.Fatal(err)
    }
}

Usage Tips

1. Task Grouping

Logically group related tasks:
// Authentication group
authTasks := []ziva.Task{
    ziva.NewInputTask("Username", "Login:"),
    ziva.NewInputTask("Password", "Password:").WithInputType(ziva.InputTypePassword),
}

// Settings group
configTasks := []ziva.Task{
    ziva.NewSingleSelectTask("Theme", themes),
    ziva.NewYesNoTask("Notifications", "Enable notifications?"),
}

queue.AddTasks(authTasks...)
queue.AddTasks(configTasks...)

2. Cancellation Handling

queue := ziva.NewQueue("Setup")
if err := queue.Run(); err != nil {
    if err == context.Canceled {
        fmt.Println("❌ Setup canceled by user")
        return
    }
    log.Fatal(err)
}

3. Configuration Saving

// After successful execution
config := collectResults(tasks...)
if err := saveConfig(config); err != nil {
    log.Printf("Save error: %v", err)
}

See Also

I