devtui

package module
v0.0.147 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 30, 2025 License: MIT Imports: 17 Imported by: 0

README

DevTUI

Project Badges

Reusable message presentation system for Go development tools. DevTUI is a pure display layer built on bubbletea that formats and organizes messages from your business logic handlers.

What DevTUI does: Takes messages from your handlers via progress() callbacks and displays them in a clean, organized terminal interface with tabs, navigation, and automatic formatting.

What DevTUI doesn't do: Validate data, handle errors, or manage business logic. Your handlers are responsible for their own state and decisions - DevTUI just shows whatever they tell it to show.

devtui

→ Why DevTUI? - Complete purpose and functionality description

Quick Start

DevTUI uses specialized handler interfaces that require minimal implementation. Here is a complete example using the new simplified API:

// HandlerExecution with MessageTracker - Action buttons with progress tracking
type BackupHandler struct {
    lastOpID string
}

func (h *BackupHandler) Name() string  { return "SystemBackup" }
func (h *BackupHandler) Label() string { return "Create System Backup" }
func (h *BackupHandler) Execute(progress func(string)) {
    progress("Preparing backup...")
    time.Sleep(200 * time.Millisecond)
    progress("Backing up database...")
    time.Sleep(500 * time.Millisecond)
    progress("Backup completed successfully")
}

// MessageTracker implementation for operation tracking
func (h *BackupHandler) GetLastOperationID() string   { return h.lastOpID }
func (h *BackupHandler) SetLastOperationID(id string) { h.lastOpID = id }

func main() {
    tui := devtui.NewTUI(&devtui.TuiConfig{
        AppName:  "Demo",
        ExitChan: make(chan bool),
        Color: &devtui.ColorStyle{
            Foreground: "#F4F4F4",
            Background: "#000000",
            Highlight:  "#FF6600",
            Lowlight:   "#666666",
        },
        LogToFile: func(messages ...any) {
            // Replace with actual logging implementation
        },
    })

    // Operations tab with ExecutionHandlers (action buttons)
    ops := tui.NewTabSection("Operations", "System Operations")
    ops.AddExecutionHandlerTracking(&BackupHandler{}, 5*time.Second)

    var wg sync.WaitGroup
    wg.Add(1)
    go tui.Start(&wg)
    wg.Wait()
}

👉 See complete example with all handler types

Handler Interfaces

DevTUI provides 5 specialized handler types, each requiring minimal implementation:

1. HandlerDisplay - Read-only Information (2 methods)
type HandlerDisplay interface {
    Name() string    // Full text to display in footer
    Content() string // Content shown immediately
}
2. HandlerEdit - Interactive Input Fields (4 methods)
    Name() string    // Unique identifier for logging
    Label() string   // Field label
    Value() string   // Current/initial value
    Change(newValue string, progress func(string))
}
3. HandlerExecution - Action Buttons (3 methods)
    Name() string  // Unique identifier for logging
    Label() string // Button label
    Execute(progress func(string))
}
4. HandlerWriter - Simple Logging (1 method)
type HandlerWriter interface {
    Name() string // Writer identifier
}
5. HandlerWriterTracker - Advanced Logging (3 methods)
type HandlerWriterTracker interface {
    Name() string
    MessageTracker
}

type MessageTracker interface {
    GetLastOperationID() string
    SetLastOperationID(id string)
}

tab.AddEditHandler(handler).WithTimeout(5time.Second) tab.AddExecutionHandler(handler).WithTimeout(10time.Second) tab.AddEditHandlerTracking(handlerWithTracker).WithTimeout(5time.Second) tab.AddExecutionHandlerTracking(handlerWithTracker).WithTimeout(10time.Second) type LogWriter struct{}

Registration Methods (New Simplified API)

// Display handlers (no timeout needed)
tab.AddDisplayHandler(handler)

// Edit handlers (timeout mandatory)
tab.AddEditHandler(handler, 5*time.Second)
tab.AddEditHandlerTracking(handlerWithTracker, 5*time.Second)

// Execution handlers (timeout mandatory)
tab.AddExecutionHandler(handler, 10*time.Second)
tab.AddExecutionHandlerTracking(handlerWithTracker, 10*time.Second)

// Writers (returns io.Writer)
type LogWriter struct{}
func (w *LogWriter) Name() string { return "LogWriter" }

writer := tab.RegisterWriterHandler(&LogWriter{}) // io.Writer
writer.Write([]byte("Log message 1"))
writer.Write([]byte("Another log entry"))

Key Features

  • Minimal Implementation: 1-4 methods per handler
  • Specialized Interfaces: Clear separation by purpose (Display, Edit, Execution, Writing)
  • Progress Callbacks: Real-time feedback for long-running operations
  • Message Tracking: Update existing messages instead of creating new ones
  • Method Chaining: All handler registration methods return *tabSection for chaining
  • Thread-Safe: Concurrent handler registration and execution

Navigation

  • Tab/Shift+Tab: Switch between tabs
  • Left/Right: Navigate fields within tab
  • Up/Down: Scroll viewport line by line
  • Page Up/Page Down: Scroll viewport page by page
  • Mouse Wheel: Scroll viewport (when available)
  • Enter: Edit/Execute
  • Esc: Cancel edit
  • Ctrl+C: Exit

Note: DevTUI automatically loads a built-in ShortcutsHandler at position 0 in the first tab, which displays detailed keyboard navigation commands. This handler demonstrates the HandlerEdit interface and provides interactive help within the application.

Text Selection: Terminal text selection is enabled for copying error messages and logs. Mouse scroll functionality may vary depending on bubbletea version and terminal capabilities.

Documentation

Acknowledgments

DevTUI is built on top of the excellent libraries from github.com/charmbracelet: bubbletea, bubbles and lipgloss, which provide the solid foundation for creating terminal interfaces in Go.

Contributing

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ColorStyle

type ColorStyle struct {
	Foreground string // eg: #F4F4F4
	Background string // eg: #000000
	Highlight  string // eg: #FF6600
	Lowlight   string // eg: #666666
}

type DevTUI

type DevTUI struct {
	*TuiConfig
	// contains filtered or unexported fields
}

DevTUI mantiene el estado de la aplicación

func NewTUI

func NewTUI(c *TuiConfig) *DevTUI

NewTUI creates a new DevTUI instance and initializes it.

Usage Example:

config := &TuiConfig{
    AppName: "MyApp",
    ExitChan: make(chan bool),
    Color: nil, // or your *ColorStyle
    LogToFile: func(err any) { fmt.Println(err) },
}
tui := NewTUI(config)

func (*DevTUI) AddTabSections added in v0.0.9

func (t *DevTUI) AddTabSections(sections ...*tabSection) *DevTUI

AddTabSections adds one or more tabSections to the DevTUI If a tab with title "DEFAULT" exists, it will be replaced by the first tab section Deprecated: Use NewTabSection and append to tabSections directly

func (*DevTUI) ContentView

func (h *DevTUI) ContentView() string

ContentView renderiza los mensajes para una sección de contenido

func (*DevTUI) GetTotalTabSections added in v0.0.9

func (t *DevTUI) GetTotalTabSections() int

GetTotalTabSections returns the total number of tab sections

func (*DevTUI) HandleKeyboard added in v0.0.10

func (h *DevTUI) HandleKeyboard(msg tea.KeyMsg) (bool, tea.Cmd)

HandleKeyboard processes keyboard input and updates the model state returns whether the update function should continue processing or return early

func (*DevTUI) Init

func (h *DevTUI) Init() tea.Cmd

Init initializes the terminal UI application.

func (*DevTUI) NewTabSection added in v0.0.43

func (t *DevTUI) NewTabSection(title, footer string) *tabSection

NewTabSection creates and initializes a new tabSection with the given title and footer NewTabSection creates a new tab section and automatically adds it to the TUI

Example:

tab := tui.NewTabSection("BUILD", "Press enter to compile")

func (*DevTUI) Print

func (h *DevTUI) Print(messages ...any)

Print sends a normal Label or error to the tui in current tab

func (*DevTUI) ReturnFocus

func (t *DevTUI) ReturnFocus() error

func (*DevTUI) SetTestMode added in v0.0.125

func (h *DevTUI) SetTestMode(enabled bool)

SetTestMode enables or disables test mode for synchronous behavior in tests. This should only be used in test files to make tests deterministic.

func (*DevTUI) Start added in v0.0.93

func (h *DevTUI) Start(args ...any)

Start initializes and runs the terminal UI application.

It accepts optional variadic arguments of any type. If a *sync.WaitGroup is provided among these arguments, Start will call its Done() method before returning.

The method runs the UI using the internal tea engine, and handles any errors that may occur during execution. If an error occurs, it will be displayed on the console and the application will wait for user input before exiting.

Parameters:

  • args ...any: Optional arguments. Can include a *sync.WaitGroup for synchronization.

func (*DevTUI) Update

func (h *DevTUI) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update maneja las actualizaciones del estado

func (*DevTUI) View

func (h *DevTUI) View() string

type HandlerDisplay added in v0.0.117

type HandlerDisplay interface {
	Name() string    // Full text to display in footer (handler responsible for content) eg. "System Status Information Display"
	Content() string // Display content (e.g., "help\n1-..\n2-...", "executing deploy wait...")
}

HandlerDisplay defines the interface for read-only information display handlers. These handlers show static or dynamic content without user interaction.

type HandlerEdit added in v0.0.117

type HandlerEdit interface {
	Name() string                                       // Identificador para logging: "ServerPort", "DatabaseURL"
	Label() string                                      // Field label (e.g., "Server Port", "Host Configuration")
	Value() string                                      // Current/initial value (e.g., "8080", "localhost")
	Change(newValue string, progress func(msgs ...any)) // Nueva firma: sin error, sin variádico, string
}

HandlerEdit defines the interface for interactive fields that accept user input. These handlers allow users to modify values through text input.

type HandlerEditTracker added in v0.0.126

type HandlerEditTracker interface {
	HandlerEdit
	MessageTracker
}

HandlerEditTracker combines HandlerEdit with MessageTracker for advanced edit handlers that need message tracking capabilities.

type HandlerExecution added in v0.0.117

type HandlerExecution interface {
	Name() string                       // Identificador para logging: "DeployProd", "BuildProject"
	Label() string                      // Button label (e.g., "Deploy to Production", "Build Project")
	Execute(progress func(msgs ...any)) // Nueva firma: sin error, sin variádico
}

HandlerExecution defines the interface for action buttons that execute operations. These handlers trigger business logic when activated by the user.

type HandlerExecutionTracker added in v0.0.126

type HandlerExecutionTracker interface {
	HandlerExecution
	MessageTracker
}

HandlerExecutionTracker combines HandlerExecution with MessageTracker for advanced execution handlers that need message tracking capabilities.

type HandlerWriter added in v0.0.103

type HandlerWriter interface {
	Name() string // Writer identifier (e.g., "webBuilder", "ApplicationLog")
}

HandlerWriter defines the interface for basic writers that create new lines for each write. These writers are suitable for simple logging or output display.

type HandlerWriterTracker added in v0.0.126

type HandlerWriterTracker interface {
	Name() string
	MessageTracker
}

HandlerWriterTracker defines the interface for advanced writers that can update existing lines. These writers support message tracking and can modify previously written content.

type MessageTracker added in v0.0.116

type MessageTracker interface {
	GetLastOperationID() string
	SetLastOperationID(id string)
}

MessageTracker provides optional interface for message tracking control. Handlers can implement this to control message updates and operation tracking.

type TuiConfig

type TuiConfig struct {
	AppName  string    // app name eg: "MyApp"
	ExitChan chan bool //  global chan to close app eg: make(chan bool)
	/*// *ColorStyle style for the TUI
	  // if nil it will use default style:
	type ColorStyle struct {
	 Foreground string // eg: #F4F4F4
	 Background string // eg: #000000
	 Highlight  string // eg: #FF6600
	 Lowlight   string // eg: #666666
	}*/
	Color *ColorStyle

	LogToFile func(messages ...any) // function to write log error
}

Directories

Path Synopsis
example
demo command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL