coal

package module
v0.0.0-...-0500d35 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

Coal: Modern Terminal UI Library for Go

中文 | English

Build beautiful, interactive command-line applications with composable components and real-time streaming support.

package main

import (
    "context"
    "github.com/voocel/coal"
)

func main() {
    ctx := context.Background()
    
    // Get user input
    name, _ := coal.Input(ctx, "What's your name?", "Enter name...")
    
    // Show progress
    coal.ShowProgress(ctx, "Processing", 100, func(update func(int)) {
        // Your work here
        for i := 0; i <= 100; i += 10 {
            update(i)
        }
    })
    
    // Display styled result
    message := coal.NewTextDisplay().
        SetText("Welcome, " + name + "!").
        SetPrefix("Success: ").
        SetStyle(coal.NewStyle().Foreground(coal.ColorGreen))
    
    fmt.Print(message.Render(ctx))
}

That's it. No complex setup, no event loop management, no manual rendering. Just create components and they work.

Go Version License Go Report Card

Why Coal?

Building terminal UIs in Go is typically complex. You need to:

  1. Handle raw terminal input/output
  2. Manage screen rendering and updates
  3. Implement component state management
  4. Deal with terminal size changes
  5. Handle concurrent user interactions

Coal handles all of this with a simple component-based API:

Without Coal With Coal
// Setup raw terminal mode
oldState, _ := term.MakeRaw(int(os.Stdin.Fd()))
defer term.Restore(int(os.Stdin.Fd()), oldState)

// Clear screen
fmt.Print("\033[2J\033[H")

// Draw input box manually
fmt.Print("┌─────────────────┐\n")
fmt.Print("│ Enter name:     │\n") 
fmt.Print("│                 │\n")
fmt.Print("└─────────────────┘\n")

// Handle input character by character
var input string
for {
    var b [1]byte
    os.Stdin.Read(b[:])
    if b[0] == 13 { // Enter
        break
    }
    if b[0] == 127 { // Backspace
        if len(input) > 0 {
            input = input[:len(input)-1]
            // Redraw everything...
        }
        continue
    }
    input += string(b[0])
    // Redraw everything...
}
name, err := coal.Input(ctx, 
    "What's your name?", 
    "Enter name...")

// That's it! Full editing support included

Install in seconds

go get github.com/voocel/coal@latest

Real-time streaming for AI applications

Perfect for LLM integrations with built-in streaming support:

// Real-time AI response streaming
stream := coal.NewAIRealTimeStream()
stream.Start()

// As each token arrives from your LLM API
for token := range llmTokens {
    stream.Append(token)  // Immediately displayed
}

stream.Complete()

Works with any streaming API:

// OpenAI streaming example
stream := coal.NewAIRealTimeStream()
stream.Start()

resp, _ := client.CreateChatCompletionStream(ctx, req)
for {
    response, err := resp.Recv()
    if err == io.EOF {
        break
    }
    stream.Append(response.Choices[0].Delta.Content)
}
stream.Complete()

Production-ready components

Input Components
// Text input with validation
input := coal.NewTextInput().
    SetMessage("Enter email:").
    SetPlaceholder("[email protected]").
    SetValidator(validateEmail).
    SetWidth(50)

// Password input
password := coal.NewPasswordInput().
    SetMessage("Password:").
    SetShowPassword(false)

// Multi-line text area
textarea := coal.NewTextArea().
    SetMessage("Description:").
    SetSize(60, 8).
    SetLineNumbers(true)
Selection Components
// Single selection
options := []coal.Option[string]{
    {Value: "go", Label: "Go", Hint: "Fast and reliable"},
    {Value: "rust", Label: "Rust", Hint: "Memory safe"},
}

selected, _ := coal.SelectOption(ctx, "Choose language:", options)

// Multi-selection
tools, _ := coal.MultiSelectOptions(ctx, "Select tools:", toolOptions)
Progress Components
// Progress bar
coal.ShowProgress(ctx, "Processing files", 100, func(update func(int)) {
    // Your work here
})

// Spinner
coal.ShowSpinner(ctx, "Loading data", func() {
    // Your work here
})

// Task sequence
tasks := []coal.Task{
    {"Initialize", func() { /* work */ }},
    {"Process", func() { /* work */ }},
    {"Complete", func() { /* work */ }},
}
coal.RunTaskSequence(ctx, tasks)
Layout Components
// Container with border
container := coal.NewContainer().
    SetTitle("User Profile").
    SetBorder(true).
    SetRounded(true).
    AddChild(userInfo).
    AddChild(statusDisplay)

// Vertical stack
vstack := coal.NewVStack().
    SetSpacing(1).
    AddChild(header).
    AddChild(content).
    AddChild(footer)

// Split layout
split := coal.NewSplit().
    SetLeft(sidebar).
    SetRight(mainContent).
    SetRatio(0.3)

Theming and styling

Built-in themes with full customization:

// Built-in themes
coal.ThemeDefault
coal.ThemeModern  
coal.ThemeGitHub
coal.ThemeVSCode
coal.ThemeDracula

// Custom styling
style := coal.NewStyle().
    Foreground(coal.ColorBlue).
    Background(coal.ColorYellow).
    SetBold(true)

text := coal.NewTextDisplay().
    SetText("Custom styled text").
    SetStyle(style)

Architecture

Coal uses an event-driven architecture with high-performance rendering:

  • 60fps differential rendering - Only updates what changed
  • Thread-safe components - Safe for concurrent use
  • Memory optimized - Object pooling and buffer reuse
  • Context-aware - Full context.Context support for cancellation
Components → Render Engine → Terminal I/O
    ↑              ↑             ↓
    └── Event System ←───────────┘

Requirements

  • Go 1.24 or later
  • Real terminal environment (Terminal.app, Command Prompt, SSH, etc.)
  • Not supported: IDE output panels, non-interactive environments

Examples

Basic CLI tool
func main() {
    ctx := context.Background()
    
    display := coal.NewTextDisplay().
        SetText("Server status: Running").
        SetPrefix("Status: ").
        SetStyle(coal.NewStyle().Foreground(coal.ColorGreen))
    
    fmt.Print(display.Render(ctx))
}
Interactive form
func collectUserInfo(ctx context.Context) {
    name, _ := coal.Input(ctx, "Name:", "Enter your name")
    
    languages := []coal.Option[string]{
        {Value: "go", Label: "Go"},
        {Value: "python", Label: "Python"},
        {Value: "rust", Label: "Rust"},
    }
    
    lang, _ := coal.SelectOption(ctx, "Favorite language:", languages)
    
    // Process results...
}
AI chat interface
func chatInterface() {
    // User input
    userMsg := coal.NewUserMessage("How does this work?")
    fmt.Print(userMsg.Render(ctx))
    
    // AI streaming response
    aiStream := coal.NewAIRealTimeStream()
    aiStream.Start()
    
    // Stream from your LLM API
    for token := range llmResponse {
        aiStream.Append(token)
    }
    
    aiStream.Complete()
}

Performance

Optimized for complex terminal applications:

  • < 1ms render time for typical components
  • < 5MB memory usage for complex UIs
  • 1000+ components supported in single application
  • 60fps smooth animations and real-time updates

Used by

Coal is designed for modern terminal applications:

  • CLI tools and utilities
  • Development environments
  • AI assistants and chat interfaces
  • Monitoring dashboards
  • Interactive installers

Contributing

We welcome contributions! See our Contributing Guide for details.

Development
git clone https://github.com/voocel/coal.git
cd coal
go mod tidy
go test ./...

# Run examples
go run examples/basic/main.go

License

MIT License - see LICENSE for details.


Built with Go for the modern terminal. Inspired by Clack and Bubble Tea.

Documentation

Index

Constants

View Source
const (
	// Direction arrows
	ArrowUp    = "↑"
	ArrowDown  = "↓"
	ArrowLeft  = "←"
	ArrowRight = "→"

	// Status symbols
	CheckMark = "✓"
	CrossMark = "✗"
	Question  = "?"
	Info      = "ⓘ"
	Warning   = "⚠"
	Error     = "✗"

	// Progress symbols
	ProgressEmpty = "░"
	ProgressFull  = "█"
	ProgressLight = "▒"
	ProgressMed   = "▓"

	// Border symbols
	BoxVertical       = "│"
	BoxHorizontal     = "─"
	BoxTopLeft        = "┌"
	BoxTopRight       = "┐"
	BoxBottomLeft     = "└"
	BoxBottomRight    = "┘"
	BoxVerticalRight  = "├"
	BoxVerticalLeft   = "┤"
	BoxHorizontalDown = "┬"
	BoxHorizontalUp   = "┴"
	BoxCross          = "┼"

	// Rounded border
	BoxRoundTopLeft     = "╭"
	BoxRoundTopRight    = "╮"
	BoxRoundBottomLeft  = "╰"
	BoxRoundBottomRight = "╯"

	// Selection symbols
	RadioSelected         = "●"
	RadioUnselected       = "○"
	CheckboxSelected      = "☑"
	CheckboxUnselected    = "☐"
	CheckboxIndeterminate = "☒"

	// Loading symbols
	SpinnerDot    = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
	SpinnerLine   = "|/-\\"
	SpinnerCircle = "◐◓◑◒"
	SpinnerSquare = "▖▘▝▗"
)

Symbols defines various Unicode symbol constants

Variables

View Source
var (
	// Basic styles
	StyleDefault = NewStyle()
	StyleBold    = NewStyle().SetBold(true)
	StyleDim     = NewStyle().SetDim(true)
	StyleItalic  = NewStyle().SetItalic(true)

	// Color styles
	StyleRed     = NewStyle().Foreground(ColorRed)
	StyleGreen   = NewStyle().Foreground(ColorGreen)
	StyleYellow  = NewStyle().Foreground(ColorYellow)
	StyleBlue    = NewStyle().Foreground(ColorBlue)
	StyleMagenta = NewStyle().Foreground(ColorMagenta)
	StyleCyan    = NewStyle().Foreground(ColorCyan)
	StyleWhite   = NewStyle().Foreground(ColorWhite)

	// Bright color styles
	StyleBrightRed     = NewStyle().Foreground(ColorBrightRed)
	StyleBrightGreen   = NewStyle().Foreground(ColorBrightGreen)
	StyleBrightYellow  = NewStyle().Foreground(ColorBrightYellow)
	StyleBrightBlue    = NewStyle().Foreground(ColorBrightBlue)
	StyleBrightMagenta = NewStyle().Foreground(ColorBrightMagenta)
	StyleBrightCyan    = NewStyle().Foreground(ColorBrightCyan)
	StyleBrightWhite   = NewStyle().Foreground(ColorBrightWhite)
)

Predefined styles

View Source
var (
	ThemeDefault = NewDefaultTheme()
	ThemeModern  = NewModernTheme()
	ThemeGitHub  = NewGitHubTheme()
	ThemeVSCode  = NewVSCodeTheme()
	ThemeDracula = NewDraculaTheme()
)
View Source
var (
	String    = StringUtils{}
	Box       = BoxUtils{}
	ProgressU = ProgressUtils{}
	ColorU    = ColorUtils{}
	InputU    = InputUtils{}
	Text      = TextUtils{}
)

Global utility instances

Functions

func Blue

func Blue(text string) string

func Bold

func Bold(text string) string

func CenterString

func CenterString(s string, width int) string

CenterString centers a string within specified width

func Clamp

func Clamp(value, min, max int) int

Clamp constrains value to specified range

func ContextWithTimeout

func ContextWithTimeout(parent context.Context, seconds int) (context.Context, context.CancelFunc)

ContextWithTimeout creates context with timeout

func Cyan

func Cyan(text string) string

func Dim

func Dim(text string) string

func DisplayWidth

func DisplayWidth(s string) int

DisplayWidth calculates the display width of a string (considering ANSI escape sequences and Unicode characters)

func FormatDuration

func FormatDuration(seconds int) string

FormatDuration formats time duration

func FormatFileSize

func FormatFileSize(size int64) string

FormatFileSize formats file size

func Green

func Green(text string) string

func Input

func Input(ctx context.Context, message, placeholder string) (string, error)

Input creates a quick text input dialog

func IsCtrlC

func IsCtrlC(key Key) bool

IsCtrlC checks if Ctrl+C is pressed

func IsEnterPressed

func IsEnterPressed(key Key) bool

IsEnterPressed checks if Enter key is pressed

func IsEscapePressed

func IsEscapePressed(key Key) bool

IsEscapePressed checks if ESC key is pressed

func IsKeyPressed

func IsKeyPressed(key Key, target string) bool

IsKeyPressed checks if specific key is pressed

func Italic

func Italic(text string) string

func ListAvailableThemes

func ListAvailableThemes() []string

func Magenta

func Magenta(text string) string

func Max

func Max(a, b int) int

Max returns the maximum value

func Min

func Min(a, b int) int

Min returns the minimum value

func PadString

func PadString(s string, width int, padChar rune) string

PadString pads string to specified width

func Password

func Password(ctx context.Context, message string) (string, error)

Password creates a quick password input dialog

func Red

func Red(text string) string

func RunTaskSequence

func RunTaskSequence(ctx context.Context, tasks []Task) error

func ShowProgress

func ShowProgress(ctx context.Context, message string, max int, work func(func(int))) error

ShowProgress displays a progress bar dialog with inline mode to avoid screen clearing issues

func ShowSpinner

func ShowSpinner(ctx context.Context, message string, work func()) error

ShowSpinner displays a spinner dialog using inline mode

func ShowSpinnerInline

func ShowSpinnerInline(ctx context.Context, message string, work func()) error

ShowSpinnerInline displays an inline spinner without clearing the screen

func TruncateString

func TruncateString(s string, maxWidth int) string

TruncateString truncates string to specified display width

func White

func White(text string) string

func WrapText

func WrapText(text string, width int) []string

WrapText wraps text to specified width

func Yellow

func Yellow(text string) string

Types

type App

type App interface {
	SetTheme(theme Theme) App
	AddComponent(component Component) App
	RemoveComponent(component Component) App
	Run(ctx context.Context) (any, error)
	SetTitle(title string) App
	SetSize(width, height int) App
}

App defines the application interface

type BoxUtils

type BoxUtils struct{}

BoxUtils provides border utility functions

func (BoxUtils) DrawBox

func (BoxUtils) DrawBox(content string, width int, rounded bool) string

DrawBox draws a border around content

func (BoxUtils) DrawHorizontalLine

func (BoxUtils) DrawHorizontalLine(width int, char string) string

DrawHorizontalLine draws a horizontal line

func (BoxUtils) DrawVerticalLine

func (BoxUtils) DrawVerticalLine(height int, char string) string

DrawVerticalLine draws a vertical line

type BufferPool

type BufferPool struct {
	// contains filtered or unexported fields
}

BufferPool provides a pool for reusing string buffers

func NewBufferPool

func NewBufferPool() *BufferPool

NewBufferPool creates a new buffer pool

func (*BufferPool) Get

func (bp *BufferPool) Get() []string

Get retrieves a buffer from the pool

func (*BufferPool) Put

func (bp *BufferPool) Put(buffer []string)

Put returns a buffer to the pool

type Color

type Color int

Color represents a color type

const (
	ColorDefault Color = iota
	ColorBlack
	ColorRed
	ColorGreen
	ColorYellow
	ColorBlue
	ColorMagenta
	ColorCyan
	ColorWhite
	ColorBrightBlack
	ColorBrightRed
	ColorBrightGreen
	ColorBrightYellow
	ColorBrightBlue
	ColorBrightMagenta
	ColorBrightCyan
	ColorBrightWhite
)

Basic color constants

type ColorUtils

type ColorUtils struct{}

ColorUtils provides color utility functions

func (ColorUtils) Gradient

func (ColorUtils) Gradient(text string, startColor, endColor Color) string

Gradient creates gradient colored text (simple implementation)

func (ColorUtils) Rainbow

func (ColorUtils) Rainbow(text string) string

Rainbow creates rainbow colored text

type Component

type Component interface {
	Render(ctx context.Context) string
	HandleEvent(event Event) error
	SetTheme(theme Theme)
	State() State
	SetState(state State)
}

Component defines the base interface for all UI components

type ConsoleReader

type ConsoleReader struct {
	// contains filtered or unexported fields
}

ConsoleReader console reader

func NewConsoleReader

func NewConsoleReader() *ConsoleReader

NewConsoleReader creates a console reader

func (*ConsoleReader) Read

func (cr *ConsoleReader) Read(p []byte) (n int, err error)

Read reads byte data

func (*ConsoleReader) ReadKey

func (cr *ConsoleReader) ReadKey() (Key, error)

ReadKey reads key events

func (*ConsoleReader) SetNonBlocking

func (cr *ConsoleReader) SetNonBlocking(nonBlocking bool) error

SetNonBlocking sets non-blocking mode

type ConsoleTerminal

type ConsoleTerminal struct {
	// contains filtered or unexported fields
}

ConsoleTerminal console terminal implementation

func (*ConsoleTerminal) Close

func (ct *ConsoleTerminal) Close() error

Close closes the terminal

func (*ConsoleTerminal) DisableRawMode

func (ct *ConsoleTerminal) DisableRawMode() error

DisableRawMode disables raw mode

func (*ConsoleTerminal) EnableRawMode

func (ct *ConsoleTerminal) EnableRawMode() error

EnableRawMode enables raw mode

func (*ConsoleTerminal) Reader

func (ct *ConsoleTerminal) Reader() Reader

Reader returns the input reader

func (*ConsoleTerminal) Size

func (ct *ConsoleTerminal) Size() (width, height int, err error)

Size gets terminal size

func (*ConsoleTerminal) Writer

func (ct *ConsoleTerminal) Writer() Writer

Writer returns the output writer

type ConsoleWriter

type ConsoleWriter struct {
	// contains filtered or unexported fields
}

ConsoleWriter console writer

func NewConsoleWriter

func NewConsoleWriter() *ConsoleWriter

NewConsoleWriter creates a console writer

func (*ConsoleWriter) Clear

func (cw *ConsoleWriter) Clear() error

Clear clears the screen

func (*ConsoleWriter) ClearFromCursor

func (cw *ConsoleWriter) ClearFromCursor() error

ClearFromCursor clears from cursor position to end of line

func (*ConsoleWriter) ClearLine

func (cw *ConsoleWriter) ClearLine() error

ClearLine clears current line

func (*ConsoleWriter) CursorDown

func (cw *ConsoleWriter) CursorDown(n int) error

CursorDown moves cursor down

func (*ConsoleWriter) CursorUp

func (cw *ConsoleWriter) CursorUp(n int) error

CursorUp moves cursor up

func (*ConsoleWriter) HideCursor

func (cw *ConsoleWriter) HideCursor() error

HideCursor hides the cursor

func (*ConsoleWriter) MoveCursor

func (cw *ConsoleWriter) MoveCursor(x, y int) error

MoveCursor moves cursor to specified position

func (*ConsoleWriter) ShowCursor

func (cw *ConsoleWriter) ShowCursor() error

ShowCursor shows the cursor

func (*ConsoleWriter) Write

func (cw *ConsoleWriter) Write(p []byte) (n int, err error)

Write writes byte data

func (*ConsoleWriter) WriteString

func (cw *ConsoleWriter) WriteString(s string) (n int, err error)

WriteString writes string

type Container

type Container struct {
	// contains filtered or unexported fields
}

Container container component

func NewContainer

func NewContainer() *Container

NewContainer creates a container

func (*Container) AddChild

func (c *Container) AddChild(child Component) *Container

AddChild adds child component

func (*Container) HandleEvent

func (c *Container) HandleEvent(event Event) error

HandleEvent handles events

func (*Container) RemoveChild

func (c *Container) RemoveChild(child Component) *Container

RemoveChild removes child component

func (*Container) Render

func (c *Container) Render(ctx context.Context) string

Render renders component

func (*Container) SetAlignment

func (c *Container) SetAlignment(alignment string) *Container

SetAlignment sets alignment

func (*Container) SetBorder

func (c *Container) SetBorder(border bool) *Container

SetBorder sets border

func (*Container) SetMargin

func (c *Container) SetMargin(margin int) *Container

SetMargin sets margin

func (*Container) SetPadding

func (c *Container) SetPadding(padding int) *Container

SetPadding sets padding

func (*Container) SetRounded

func (c *Container) SetRounded(rounded bool) *Container

SetRounded sets rounded corners

func (*Container) SetSize

func (c *Container) SetSize(width, height int) *Container

SetSize sets size

func (*Container) SetState

func (c *Container) SetState(state State)

SetState sets state

func (*Container) SetTheme

func (c *Container) SetTheme(theme Theme)

SetTheme sets theme

func (*Container) SetTitle

func (c *Container) SetTitle(title string) *Container

SetTitle sets title

func (*Container) State

func (c *Container) State() State

State gets state

type CustomTheme

type CustomTheme struct {
	// contains filtered or unexported fields
}

CustomTheme represents a custom theme builder

func NewCustomTheme

func NewCustomTheme(name string) *CustomTheme

func (*CustomTheme) Background

func (t *CustomTheme) Background() Style

func (*CustomTheme) Border

func (t *CustomTheme) Border() Style

func (*CustomTheme) Build

func (t *CustomTheme) Build() Theme

func (*CustomTheme) Error

func (t *CustomTheme) Error() Style

func (*CustomTheme) Focused

func (t *CustomTheme) Focused() Style

func (*CustomTheme) Foreground

func (t *CustomTheme) Foreground() Style

func (*CustomTheme) Info

func (t *CustomTheme) Info() Style

func (*CustomTheme) Name

func (t *CustomTheme) Name() string

func (*CustomTheme) Primary

func (t *CustomTheme) Primary() Style

func (*CustomTheme) Secondary

func (t *CustomTheme) Secondary() Style

func (*CustomTheme) SetBackground

func (t *CustomTheme) SetBackground(style Style) *CustomTheme

func (*CustomTheme) SetBorder

func (t *CustomTheme) SetBorder(style Style) *CustomTheme

func (*CustomTheme) SetError

func (t *CustomTheme) SetError(style Style) *CustomTheme

func (*CustomTheme) SetFocused

func (t *CustomTheme) SetFocused(style Style) *CustomTheme

func (*CustomTheme) SetForeground

func (t *CustomTheme) SetForeground(style Style) *CustomTheme

func (*CustomTheme) SetInfo

func (t *CustomTheme) SetInfo(style Style) *CustomTheme

func (*CustomTheme) SetPrimary

func (t *CustomTheme) SetPrimary(style Style) *CustomTheme

func (*CustomTheme) SetSecondary

func (t *CustomTheme) SetSecondary(style Style) *CustomTheme

func (*CustomTheme) SetSuccess

func (t *CustomTheme) SetSuccess(style Style) *CustomTheme

func (*CustomTheme) SetWarning

func (t *CustomTheme) SetWarning(style Style) *CustomTheme

func (*CustomTheme) Success

func (t *CustomTheme) Success() Style

func (*CustomTheme) Warning

func (t *CustomTheme) Warning() Style

type DefaultTheme

type DefaultTheme struct {
	// contains filtered or unexported fields
}

DefaultTheme represents the default theme

func (*DefaultTheme) Background

func (t *DefaultTheme) Background() Style

func (*DefaultTheme) Border

func (t *DefaultTheme) Border() Style

func (*DefaultTheme) Error

func (t *DefaultTheme) Error() Style

func (*DefaultTheme) Focused

func (t *DefaultTheme) Focused() Style

func (*DefaultTheme) Foreground

func (t *DefaultTheme) Foreground() Style

func (*DefaultTheme) Info

func (t *DefaultTheme) Info() Style

func (*DefaultTheme) Name

func (t *DefaultTheme) Name() string

func (*DefaultTheme) Primary

func (t *DefaultTheme) Primary() Style

func (*DefaultTheme) Secondary

func (t *DefaultTheme) Secondary() Style

func (*DefaultTheme) Success

func (t *DefaultTheme) Success() Style

func (*DefaultTheme) Warning

func (t *DefaultTheme) Warning() Style

type DiffCache

type DiffCache struct {
	// contains filtered or unexported fields
}

DiffCache provides differential caching for rendering performance optimization

func NewDiffCache

func NewDiffCache(maxSize int) *DiffCache

NewDiffCache creates a new differential cache

func (*DiffCache) Clear

func (dc *DiffCache) Clear()

Clear empties the cache

func (*DiffCache) Get

func (dc *DiffCache) Get(key string) (string, bool)

Get retrieves a cached value

func (*DiffCache) Set

func (dc *DiffCache) Set(key, value string)

Set stores a value in cache

type DraculaTheme

type DraculaTheme struct {
	// contains filtered or unexported fields
}

DraculaTheme represents a Dracula theme

func (*DraculaTheme) Background

func (t *DraculaTheme) Background() Style

func (*DraculaTheme) Border

func (t *DraculaTheme) Border() Style

func (*DraculaTheme) Error

func (t *DraculaTheme) Error() Style

func (*DraculaTheme) Focused

func (t *DraculaTheme) Focused() Style

func (*DraculaTheme) Foreground

func (t *DraculaTheme) Foreground() Style

func (*DraculaTheme) Info

func (t *DraculaTheme) Info() Style

func (*DraculaTheme) Name

func (t *DraculaTheme) Name() string

func (*DraculaTheme) Primary

func (t *DraculaTheme) Primary() Style

func (*DraculaTheme) Secondary

func (t *DraculaTheme) Secondary() Style

func (*DraculaTheme) Success

func (t *DraculaTheme) Success() Style

func (*DraculaTheme) Warning

func (t *DraculaTheme) Warning() Style

type Engine

type Engine interface {
	Start(ctx context.Context) error
	Stop() error
	Render(component Component) error
	SetTerminal(terminal Terminal)
	AddComponent(component Component)
	RemoveComponent(component Component) error
}

Engine defines the rendering engine interface

type Event

type Event struct {
	Type      EventType
	Key       Key // Key info when Type is EventTypeKey
	Data      any // Additional event data
	Timestamp time.Time
	Source    Component
}

Event represents a system or user event

type EventBus

type EventBus struct {
	// contains filtered or unexported fields
}

EventBus represents an event bus

func NewEventBus

func NewEventBus(bufferSize int) *EventBus

NewEventBus creates a new event bus

func (*EventBus) Publish

func (eb *EventBus) Publish(event Event) bool

Publish publishes an event (non-blocking)

func (*EventBus) PublishBlocking

func (eb *EventBus) PublishBlocking(event Event) error

PublishBlocking publishes an event (blocking)

func (*EventBus) Start

func (eb *EventBus) Start()

Start starts the event processing loop

func (*EventBus) Stop

func (eb *EventBus) Stop()

Stop stops the event bus

func (*EventBus) Subscribe

func (eb *EventBus) Subscribe(eventType EventType, handler EventHandler)

Subscribe subscribes to events

func (*EventBus) Unsubscribe

func (eb *EventBus) Unsubscribe(eventType EventType)

Unsubscribe unsubscribes from events (removes all handlers of this type)

type EventEmitter

type EventEmitter struct {
	// contains filtered or unexported fields
}

EventEmitter represents an event emitter

func NewEventEmitter

func NewEventEmitter(bus *EventBus) *EventEmitter

NewEventEmitter creates an event emitter

func (*EventEmitter) EmitCustom

func (ee *EventEmitter) EmitCustom(data any, source Component)

EmitCustom emits a custom event

func (*EventEmitter) EmitKey

func (ee *EventEmitter) EmitKey(key Key, source Component)

EmitKey emits a key event

func (*EventEmitter) EmitMouse

func (ee *EventEmitter) EmitMouse(data any, source Component)

EmitMouse emits a mouse event

func (*EventEmitter) EmitResize

func (ee *EventEmitter) EmitResize(width, height int, source Component)

EmitResize emits a window resize event

func (*EventEmitter) EmitTimer

func (ee *EventEmitter) EmitTimer(data any, source Component)

EmitTimer emits a timer event

type EventHandler

type EventHandler func(event Event) error

type EventType

type EventType int
const (
	EventTypeKey EventType = iota
	EventTypeResize
	EventTypeMouse
	EventTypeTimer
	EventTypeCustom
)

type GitHubTheme

type GitHubTheme struct {
	// contains filtered or unexported fields
}

GitHubTheme represents a GitHub-style theme

func (*GitHubTheme) Background

func (t *GitHubTheme) Background() Style

func (*GitHubTheme) Border

func (t *GitHubTheme) Border() Style

func (*GitHubTheme) Error

func (t *GitHubTheme) Error() Style

func (*GitHubTheme) Focused

func (t *GitHubTheme) Focused() Style

func (*GitHubTheme) Foreground

func (t *GitHubTheme) Foreground() Style

func (*GitHubTheme) Info

func (t *GitHubTheme) Info() Style

func (*GitHubTheme) Name

func (t *GitHubTheme) Name() string

func (*GitHubTheme) Primary

func (t *GitHubTheme) Primary() Style

func (*GitHubTheme) Secondary

func (t *GitHubTheme) Secondary() Style

func (*GitHubTheme) Success

func (t *GitHubTheme) Success() Style

func (*GitHubTheme) Warning

func (t *GitHubTheme) Warning() Style

type HStack

type HStack struct {
	// contains filtered or unexported fields
}

HStack horizontal stack layout

func NewHStack

func NewHStack() *HStack

NewHStack creates horizontal stack layout

func (*HStack) AddChild

func (h *HStack) AddChild(child Component) *HStack

AddChild adds child component

func (*HStack) HandleEvent

func (h *HStack) HandleEvent(event Event) error

HandleEvent handles events

func (*HStack) Render

func (h *HStack) Render(ctx context.Context) string

Render renders component

func (*HStack) SetAlignment

func (h *HStack) SetAlignment(alignment string) *HStack

SetAlignment sets alignment

func (*HStack) SetSpacing

func (h *HStack) SetSpacing(spacing int) *HStack

SetSpacing sets spacing

func (*HStack) SetState

func (h *HStack) SetState(state State)

SetState sets state

func (*HStack) SetTheme

func (h *HStack) SetTheme(theme Theme)

SetTheme sets theme

func (*HStack) State

func (h *HStack) State() State

State gets state

type InputUtils

type InputUtils struct{}

InputUtils provides input-related utility functions

func (InputUtils) IsAlphaNumeric

func (InputUtils) IsAlphaNumeric(r rune) bool

IsAlphaNumeric checks if character is alphanumeric

func (InputUtils) IsControlChar

func (InputUtils) IsControlChar(r rune) bool

IsControlChar checks if character is a control character

func (InputUtils) IsPrintable

func (InputUtils) IsPrintable(r rune) bool

IsPrintable checks if character is printable

func (InputUtils) SanitizeInput

func (InputUtils) SanitizeInput(s string) string

SanitizeInput cleans input text

func (InputUtils) ValidateEmail

func (InputUtils) ValidateEmail(email string) bool

ValidateEmail performs simple email validation

type Key

type Key struct {
	Name  string // Key name (e.g. "a", "enter", "escape")
	Rune  rune   // Unicode character
	Ctrl  bool   // Ctrl key pressed
	Alt   bool   // Alt key pressed
	Shift bool   // Shift key pressed
	Meta  bool   // Meta key pressed (macOS Command key)
}

Key represents a keyboard input

func ParseKeySequence

func ParseKeySequence(sequence string) []Key

ParseKeySequence parses key sequence string

type KeyEventManager

type KeyEventManager struct {
	// contains filtered or unexported fields
}

KeyEventManager manages key events

func NewKeyEventManager

func NewKeyEventManager(emitter *EventEmitter) *KeyEventManager

NewKeyEventManager creates a key event manager

func (*KeyEventManager) BindKey

func (km *KeyEventManager) BindKey(keyName string, handler EventHandler)

BindKey binds a key handler

func (*KeyEventManager) HandleKeyEvent

func (km *KeyEventManager) HandleKeyEvent(event Event) error

HandleKeyEvent handles key events

func (*KeyEventManager) UnbindKey

func (km *KeyEventManager) UnbindKey(keyName string)

UnbindKey unbinds a key handler

type LoadingIndicator

type LoadingIndicator struct {
	// contains filtered or unexported fields
}

LoadingIndicator represents a composite loading indicator

func NewLoadingIndicator

func NewLoadingIndicator() *LoadingIndicator

func (*LoadingIndicator) HandleEvent

func (l *LoadingIndicator) HandleEvent(event Event) error

func (*LoadingIndicator) Render

func (l *LoadingIndicator) Render(ctx context.Context) string

func (*LoadingIndicator) SetMessage

func (l *LoadingIndicator) SetMessage(message string) *LoadingIndicator

func (*LoadingIndicator) SetProgress

func (l *LoadingIndicator) SetProgress(current, max int) *LoadingIndicator

func (*LoadingIndicator) SetShowProgress

func (l *LoadingIndicator) SetShowProgress(show bool) *LoadingIndicator

func (*LoadingIndicator) SetState

func (l *LoadingIndicator) SetState(state State)

func (*LoadingIndicator) SetTheme

func (l *LoadingIndicator) SetTheme(theme Theme)

func (*LoadingIndicator) Start

func (l *LoadingIndicator) Start(message string) *LoadingIndicator

func (*LoadingIndicator) State

func (l *LoadingIndicator) State() State

func (*LoadingIndicator) Stop

func (l *LoadingIndicator) Stop(message string, success bool) *LoadingIndicator

type MockReader

type MockReader struct {
	// contains filtered or unexported fields
}

MockReader mock reader

func NewMockReader

func NewMockReader() *MockReader

NewMockReader creates a mock reader

func (*MockReader) Read

func (mr *MockReader) Read(p []byte) (n int, err error)

Read reads byte data

func (*MockReader) ReadKey

func (mr *MockReader) ReadKey() (Key, error)

ReadKey reads key

func (*MockReader) SetKeySequence

func (mr *MockReader) SetKeySequence(keys []Key)

SetKeySequence sets key sequence

func (*MockReader) SetNonBlocking

func (mr *MockReader) SetNonBlocking(nonBlocking bool) error

SetNonBlocking sets non-blocking mode

type MockTerminal

type MockTerminal struct {
	// contains filtered or unexported fields
}

MockTerminal mock terminal for testing

func NewMockTerminal

func NewMockTerminal() *MockTerminal

NewMockTerminal creates a mock terminal

func (*MockTerminal) Close

func (mt *MockTerminal) Close() error

Close closes the terminal

func (*MockTerminal) DisableRawMode

func (mt *MockTerminal) DisableRawMode() error

DisableRawMode disables raw mode

func (*MockTerminal) EnableRawMode

func (mt *MockTerminal) EnableRawMode() error

EnableRawMode enables raw mode

func (*MockTerminal) GetOutput

func (mt *MockTerminal) GetOutput() []string

GetOutput gets output content

func (*MockTerminal) Reader

func (mt *MockTerminal) Reader() Reader

Reader returns mock reader

func (*MockTerminal) SetKeySequence

func (mt *MockTerminal) SetKeySequence(keys []Key)

SetKeySequence sets key sequence

func (*MockTerminal) Size

func (mt *MockTerminal) Size() (width, height int, err error)

Size returns terminal size

func (*MockTerminal) Writer

func (mt *MockTerminal) Writer() Writer

Writer returns mock writer

type MockWriter

type MockWriter struct {
	// contains filtered or unexported fields
}

MockWriter mock writer

func NewMockWriter

func NewMockWriter() *MockWriter

NewMockWriter creates a mock writer

func (*MockWriter) Clear

func (mw *MockWriter) Clear() error

Clear clears screen

func (*MockWriter) GetAllOutput

func (mw *MockWriter) GetAllOutput() string

GetAllOutput gets all output combined as single string

func (*MockWriter) GetLastOutput

func (mw *MockWriter) GetLastOutput() string

GetLastOutput gets last output

func (*MockWriter) GetOutput

func (mw *MockWriter) GetOutput() []string

GetOutput gets all output

func (*MockWriter) HideCursor

func (mw *MockWriter) HideCursor() error

HideCursor hides cursor

func (*MockWriter) MoveCursor

func (mw *MockWriter) MoveCursor(x, y int) error

MoveCursor moves cursor

func (*MockWriter) Reset

func (mw *MockWriter) Reset()

Reset resets output

func (*MockWriter) ShowCursor

func (mw *MockWriter) ShowCursor() error

ShowCursor shows cursor

func (*MockWriter) Write

func (mw *MockWriter) Write(p []byte) (n int, err error)

Write writes byte data

func (*MockWriter) WriteString

func (mw *MockWriter) WriteString(s string) (n int, err error)

WriteString writes string

type ModernTheme

type ModernTheme struct {
	// contains filtered or unexported fields
}

ModernTheme represents a modern theme

func (*ModernTheme) Background

func (t *ModernTheme) Background() Style

func (*ModernTheme) Border

func (t *ModernTheme) Border() Style

func (*ModernTheme) Error

func (t *ModernTheme) Error() Style

func (*ModernTheme) Focused

func (t *ModernTheme) Focused() Style

func (*ModernTheme) Foreground

func (t *ModernTheme) Foreground() Style

func (*ModernTheme) Info

func (t *ModernTheme) Info() Style

func (*ModernTheme) Name

func (t *ModernTheme) Name() string

func (*ModernTheme) Primary

func (t *ModernTheme) Primary() Style

func (*ModernTheme) Secondary

func (t *ModernTheme) Secondary() Style

func (*ModernTheme) Success

func (t *ModernTheme) Success() Style

func (*ModernTheme) Warning

func (t *ModernTheme) Warning() Style

type MultiSelect

type MultiSelect[T any] struct {
	*Select[T]
	// contains filtered or unexported fields
}

MultiSelect represents a multi-selection component

func NewMultiSelect

func NewMultiSelect[T any]() *MultiSelect[T]

NewMultiSelect creates a new multi-select component

func (*MultiSelect[T]) GetSelectedValues

func (m *MultiSelect[T]) GetSelectedValues() []T

GetSelectedValues returns all selected values

func (*MultiSelect[T]) HandleEvent

func (m *MultiSelect[T]) HandleEvent(event Event) error

HandleEvent handles events for multi-select

func (*MultiSelect[T]) OnSelectionChange

func (m *MultiSelect[T]) OnSelectionChange(callback func([]T)) *MultiSelect[T]

OnSelectionChange sets the selection change callback

type Option

type Option[T any] struct {
	Value    T      // Option value
	Label    string // Display label
	Hint     string // Hint text
	Disabled bool   // Whether disabled
}

Option represents a selectable item

type PasswordInput

type PasswordInput struct {
	*TextInput
	// contains filtered or unexported fields
}

PasswordInput represents a password input component

func NewPasswordInput

func NewPasswordInput() *PasswordInput

NewPasswordInput creates a password input component

func (*PasswordInput) SetShowPassword

func (p *PasswordInput) SetShowPassword(show bool) *PasswordInput

SetShowPassword sets whether to show password

func (*PasswordInput) TogglePasswordVisibility

func (p *PasswordInput) TogglePasswordVisibility()

TogglePasswordVisibility toggles password visibility

type ProgressBar

type ProgressBar struct {
	// contains filtered or unexported fields
}

ProgressBar represents a progress bar component

func NewProgressBar

func NewProgressBar() *ProgressBar

func (*ProgressBar) Finish

func (p *ProgressBar) Finish(message string) *ProgressBar

func (*ProgressBar) GetProgress

func (p *ProgressBar) GetProgress() (current, max int, percentage float64)

func (*ProgressBar) HandleEvent

func (p *ProgressBar) HandleEvent(event Event) error

func (*ProgressBar) Increment

func (p *ProgressBar) Increment(delta int) *ProgressBar

func (*ProgressBar) Render

func (p *ProgressBar) Render(ctx context.Context) string

func (*ProgressBar) SetCurrent

func (p *ProgressBar) SetCurrent(current int) *ProgressBar

func (*ProgressBar) SetMax

func (p *ProgressBar) SetMax(max int) *ProgressBar

func (*ProgressBar) SetMessage

func (p *ProgressBar) SetMessage(message string) *ProgressBar

func (*ProgressBar) SetShowPercent

func (p *ProgressBar) SetShowPercent(show bool) *ProgressBar

func (*ProgressBar) SetShowValue

func (p *ProgressBar) SetShowValue(show bool) *ProgressBar

func (*ProgressBar) SetState

func (p *ProgressBar) SetState(state State)

func (*ProgressBar) SetStyle

func (p *ProgressBar) SetStyle(style string) *ProgressBar

func (*ProgressBar) SetTheme

func (p *ProgressBar) SetTheme(theme Theme)

func (*ProgressBar) SetWidth

func (p *ProgressBar) SetWidth(width int) *ProgressBar

func (*ProgressBar) Start

func (p *ProgressBar) Start(message string) *ProgressBar

func (*ProgressBar) State

func (p *ProgressBar) State() State

type ProgressUtils

type ProgressUtils struct{}

ProgressUtils provides progress-related utility functions

func (ProgressUtils) DrawProgressBar

func (ProgressUtils) DrawProgressBar(current, max, width int, style string) string

DrawProgressBar draws a progress bar

func (ProgressUtils) GetSpinnerFrame

func (ProgressUtils) GetSpinnerFrame(frameIndex int, style string) string

GetSpinnerFrame gets a loading animation frame

type Reader

type Reader interface {
	Read(p []byte) (n int, err error)
	ReadKey() (Key, error)
	SetNonBlocking(nonBlocking bool) error
}

Reader defines input reading interface

type RealTimeStream

type RealTimeStream struct {
	// contains filtered or unexported fields
}

RealTimeStream real-time streaming component - suitable for real AI application scenarios

func NewAIRealTimeStream

func NewAIRealTimeStream() *RealTimeStream

NewAIRealTimeStream creates AI-specific real-time streaming component

func NewRealTimeStream

func NewRealTimeStream() *RealTimeStream

NewRealTimeStream creates real-time streaming component

func NewSystemRealTimeStream

func NewSystemRealTimeStream() *RealTimeStream

NewSystemRealTimeStream creates system-specific real-time streaming component

func NewUserRealTimeStream

func NewUserRealTimeStream() *RealTimeStream

NewUserRealTimeStream creates user-specific real-time streaming component (though users typically don't need streaming)

func (*RealTimeStream) Append

func (rts *RealTimeStream) Append(chunk string) *RealTimeStream

Append appends and immediately displays new text chunk

func (*RealTimeStream) Clear

func (rts *RealTimeStream) Clear() *RealTimeStream

Clear clears content

func (*RealTimeStream) Complete

func (rts *RealTimeStream) Complete()

Complete marks streaming display as finished

func (*RealTimeStream) GetContent

func (rts *RealTimeStream) GetContent() string

GetContent gets current accumulated complete content

func (*RealTimeStream) HandleEvent

func (rts *RealTimeStream) HandleEvent(event Event) error

HandleEvent handles events

func (*RealTimeStream) OnChunk

func (rts *RealTimeStream) OnChunk(callback func(chunk string)) *RealTimeStream

OnChunk sets chunk callback

func (*RealTimeStream) OnComplete

func (rts *RealTimeStream) OnComplete(callback func(content string)) *RealTimeStream

OnComplete sets completion callback

func (*RealTimeStream) OnStart

func (rts *RealTimeStream) OnStart(callback func()) *RealTimeStream

OnStart sets start callback

func (*RealTimeStream) Render

func (rts *RealTimeStream) Render(ctx context.Context) string

Render renders component (returns complete content)

func (*RealTimeStream) SetMaxWidth

func (rts *RealTimeStream) SetMaxWidth(width int) *RealTimeStream

SetMaxWidth sets maximum width

func (*RealTimeStream) SetPrefix

func (rts *RealTimeStream) SetPrefix(prefix string) *RealTimeStream

SetPrefix sets prefix

func (*RealTimeStream) SetPrefixStyle

func (rts *RealTimeStream) SetPrefixStyle(style Style) *RealTimeStream

SetPrefixStyle sets prefix style

func (*RealTimeStream) SetState

func (rts *RealTimeStream) SetState(state State)

SetState sets state

func (*RealTimeStream) SetStyle

func (rts *RealTimeStream) SetStyle(style Style) *RealTimeStream

SetStyle sets text style

func (*RealTimeStream) SetTheme

func (rts *RealTimeStream) SetTheme(theme Theme)

SetTheme sets theme

func (*RealTimeStream) Start

func (rts *RealTimeStream) Start()

Start begins streaming display (shows prefix)

func (*RealTimeStream) State

func (rts *RealTimeStream) State() State

State gets state

type RenderEngine

type RenderEngine struct {
	// contains filtered or unexported fields
}

RenderEngine implements the rendering engine

func NewRenderEngine

func NewRenderEngine() *RenderEngine

func (*RenderEngine) AddComponent

func (re *RenderEngine) AddComponent(component Component)

AddComponent adds a component to the render engine

func (*RenderEngine) RemoveComponent

func (re *RenderEngine) RemoveComponent(component Component) error

RemoveComponent removes a component from the render engine

func (*RenderEngine) Render

func (re *RenderEngine) Render(component Component) error

func (*RenderEngine) SetTerminal

func (re *RenderEngine) SetTerminal(terminal Terminal)

SetTerminal sets the terminal for rendering

func (*RenderEngine) Start

func (re *RenderEngine) Start(ctx context.Context) error

func (*RenderEngine) Stop

func (re *RenderEngine) Stop() error

type RenderFunc

type RenderFunc func(ctx context.Context) string

type Select

type Select[T any] struct {
	// contains filtered or unexported fields
}

Select represents a single selection component

func NewSelect

func NewSelect[T any]() *Select[T]

NewSelect creates a new select component

func (*Select[T]) AddOption

func (s *Select[T]) AddOption(value T, label, hint string) *Select[T]

AddOption adds an option to the select

func (*Select[T]) Blur

func (s *Select[T]) Blur()

Blur removes focus from the component

func (*Select[T]) Focus

func (s *Select[T]) Focus()

Focus gives focus to the component

func (*Select[T]) GetSelectedValue

func (s *Select[T]) GetSelectedValue() (T, bool)

GetSelectedValue returns the selected value

func (*Select[T]) HandleEvent

func (s *Select[T]) HandleEvent(event Event) error

HandleEvent handles events

func (*Select[T]) OnCancel

func (s *Select[T]) OnCancel(callback func()) *Select[T]

OnCancel sets the cancel callback

func (*Select[T]) OnChange

func (s *Select[T]) OnChange(callback func(T)) *Select[T]

OnChange sets the selection change callback

func (*Select[T]) OnSubmit

func (s *Select[T]) OnSubmit(callback func(T)) *Select[T]

OnSubmit sets the submit callback

func (*Select[T]) Render

func (s *Select[T]) Render(ctx context.Context) string

Render renders the select component

func (*Select[T]) SetMaxItems

func (s *Select[T]) SetMaxItems(maxItems int) *Select[T]

SetMaxItems sets the maximum number of items to display

func (*Select[T]) SetMessage

func (s *Select[T]) SetMessage(message string) *Select[T]

SetMessage sets the message text

func (*Select[T]) SetOptions

func (s *Select[T]) SetOptions(options []Option[T]) *Select[T]

SetOptions sets all options for the select

func (*Select[T]) SetSearchable

func (s *Select[T]) SetSearchable(searchable bool) *Select[T]

SetSearchable sets whether the select is searchable

func (*Select[T]) SetState

func (s *Select[T]) SetState(state State)

SetState sets the state

func (*Select[T]) SetTheme

func (s *Select[T]) SetTheme(theme Theme)

SetTheme sets the theme

func (*Select[T]) SetWidth

func (s *Select[T]) SetWidth(width int) *Select[T]

SetWidth sets the component width

func (*Select[T]) State

func (s *Select[T]) State() State

State returns the current state

type Spinner

type Spinner struct {
	// contains filtered or unexported fields
}

Spinner represents a loading spinner component

func NewSpinner

func NewSpinner() *Spinner

func (*Spinner) HandleEvent

func (s *Spinner) HandleEvent(event Event) error

func (*Spinner) IsRunning

func (s *Spinner) IsRunning() bool

func (*Spinner) Render

func (s *Spinner) Render(ctx context.Context) string

func (*Spinner) SetInterval

func (s *Spinner) SetInterval(interval time.Duration) *Spinner

func (*Spinner) SetMessage

func (s *Spinner) SetMessage(message string) *Spinner

func (*Spinner) SetState

func (s *Spinner) SetState(state State)

func (*Spinner) SetStyle

func (s *Spinner) SetStyle(style string) *Spinner

func (*Spinner) SetTheme

func (s *Spinner) SetTheme(theme Theme)

func (*Spinner) Start

func (s *Spinner) Start(message string) *Spinner

func (*Spinner) State

func (s *Spinner) State() State

func (*Spinner) Stop

func (s *Spinner) Stop(message string, success bool) *Spinner

type Split

type Split struct {
	// contains filtered or unexported fields
}

Split split layout component

func NewSplit

func NewSplit() *Split

NewSplit creates split layout

func (*Split) HandleEvent

func (s *Split) HandleEvent(event Event) error

HandleEvent handles events

func (*Split) Render

func (s *Split) Render(ctx context.Context) string

Render renders component

func (*Split) SetLeft

func (s *Split) SetLeft(component Component) *Split

SetLeft sets left component

func (*Split) SetOrientation

func (s *Split) SetOrientation(orientation string) *Split

SetOrientation sets orientation

func (*Split) SetRatio

func (s *Split) SetRatio(ratio float64) *Split

SetRatio sets split ratio

func (*Split) SetRight

func (s *Split) SetRight(component Component) *Split

SetRight sets right component

func (*Split) SetSeparator

func (s *Split) SetSeparator(separator bool) *Split

SetSeparator sets whether to show separator

func (*Split) SetSize

func (s *Split) SetSize(width, height int) *Split

SetSize sets size

func (*Split) SetState

func (s *Split) SetState(state State)

SetState sets state

func (*Split) SetTheme

func (s *Split) SetTheme(theme Theme)

SetTheme sets theme

func (*Split) State

func (s *Split) State() State

State gets state

type State

type State struct {
	Type     StateType
	Value    any
	Error    error
	Cursor   int   // Cursor position
	Selected []int // Selected item indices for multi-select components
	Focused  bool  // Whether component has focus
	Visible  bool  // Whether component is visible
	Dirty    bool  // Whether component needs re-rendering
}

State represents component state

type StateManager

type StateManager struct {
	// contains filtered or unexported fields
}

StateManager manages component state

func NewStateManager

func NewStateManager() *StateManager

NewStateManager creates a state manager

func (*StateManager) GetState

func (sm *StateManager) GetState(component Component) State

GetState gets component state

func (*StateManager) ListStates

func (sm *StateManager) ListStates() map[Component]State

ListStates lists all states

func (*StateManager) RemoveState

func (sm *StateManager) RemoveState(component Component)

RemoveState removes component state

func (*StateManager) SetState

func (sm *StateManager) SetState(component Component, state State)

SetState sets component state

func (*StateManager) UpdateState

func (sm *StateManager) UpdateState(component Component, updateFunc func(State) State)

UpdateState updates component state

type StateType

type StateType int
const (
	StateInitial StateType = iota
	StateActive
	StateSubmit
	StateCancel
	StateError
	StateDisabled
)

type StringUtils

type StringUtils struct{}

StringUtils provides string utility functions

func (StringUtils) CountLines

func (StringUtils) CountLines(s string) int

CountLines counts the number of lines in string

func (StringUtils) IsEmpty

func (StringUtils) IsEmpty(s string) bool

IsEmpty checks if string is empty (including whitespace-only)

func (StringUtils) JoinLines

func (StringUtils) JoinLines(lines []string) string

JoinLines joins multi-line text

func (StringUtils) PadCenter

func (StringUtils) PadCenter(s string, width int, padChar rune) string

PadCenter centers string with padding

func (StringUtils) PadLeft

func (StringUtils) PadLeft(s string, width int, padChar rune) string

PadLeft pads string on the left

func (StringUtils) PadRight

func (StringUtils) PadRight(s string, width int, padChar rune) string

PadRight pads string on the right

func (StringUtils) RemoveAnsiCodes

func (StringUtils) RemoveAnsiCodes(s string) string

RemoveAnsiCodes removes ANSI escape sequences

func (StringUtils) Repeat

func (StringUtils) Repeat(s string, count int) string

Repeat repeats a string

func (StringUtils) SplitLines

func (StringUtils) SplitLines(s string) []string

SplitLines splits multi-line text

func (StringUtils) Truncate

func (StringUtils) Truncate(s string, maxWidth int, suffix string) string

Truncate truncates string to specified width

type Style

type Style struct {
	FgColor       Color // Foreground color
	BgColor       Color // Background color
	Bold          bool  // Bold text
	Italic        bool  // Italic text
	Underline     bool  // Underlined text
	Strikethrough bool  // Strikethrough text
	Dim           bool  // Dimmed text
	Blink         bool  // Blinking text
	Reverse       bool  // Reverse foreground and background colors
}

Style defines text styling options

func NewStyle

func NewStyle() Style

NewStyle creates a new style

func (Style) Apply

func (s Style) Apply(text string) string

Apply applies the style to text

func (Style) Background

func (s Style) Background(color Color) Style

Background sets background color

func (Style) Foreground

func (s Style) Foreground(color Color) Style

Foreground sets foreground color

func (s Style) SetBlink(blink bool) Style

SetBlink sets blinking text

func (Style) SetBold

func (s Style) SetBold(bold bool) Style

SetBold sets bold text

func (Style) SetDim

func (s Style) SetDim(dim bool) Style

SetDim sets dimmed text

func (Style) SetItalic

func (s Style) SetItalic(italic bool) Style

SetItalic sets italic text

func (Style) SetReverse

func (s Style) SetReverse(reverse bool) Style

SetReverse sets reverse video

func (Style) SetStrikethrough

func (s Style) SetStrikethrough(strikethrough bool) Style

SetStrikethrough sets strikethrough text

func (Style) SetUnderline

func (s Style) SetUnderline(underline bool) Style

SetUnderline sets underlined text

func (Style) String

func (s Style) String() string

String returns string representation of the style

type Task

type Task struct {
	Name string
	Work func()
}

type Terminal

type Terminal interface {
	Reader() Reader
	Writer() Writer
	Size() (width, height int, err error)
	EnableRawMode() error
	DisableRawMode() error
	Close() error
}

Terminal abstracts terminal I/O operations

func NewTerminal

func NewTerminal() (Terminal, error)

NewTerminal creates a new terminal instance

type TextArea

type TextArea struct {
	*TextInput
	// contains filtered or unexported fields
}

TextArea represents a multi-line text input component

func NewTextArea

func NewTextArea() *TextArea

NewTextArea creates a multi-line text input component

func (*TextArea) ScrollDown

func (t *TextArea) ScrollDown()

ScrollDown scrolls down

func (*TextArea) ScrollUp

func (t *TextArea) ScrollUp()

ScrollUp scrolls up

func (*TextArea) SetLineNumbers

func (t *TextArea) SetLineNumbers(show bool) *TextArea

SetLineNumbers sets whether to show line numbers

type TextDisplay

type TextDisplay struct {
	// contains filtered or unexported fields
}

TextDisplay general text display component

func NewAIMessage

func NewAIMessage(text string) *TextDisplay

NewAIMessage creates AI message style TextDisplay

func NewCodeBlock

func NewCodeBlock(code string) *TextDisplay

NewCodeBlock creates code block style TextDisplay

func NewSystemMessage

func NewSystemMessage(text string) *TextDisplay

NewSystemMessage creates system message style TextDisplay

func NewTextDisplay

func NewTextDisplay() *TextDisplay

NewTextDisplay creates a new text display component

func NewUserMessage

func NewUserMessage(text string) *TextDisplay

NewUserMessage creates user message style TextDisplay

func (*TextDisplay) GetText

func (td *TextDisplay) GetText() string

GetText gets text content

func (*TextDisplay) HandleEvent

func (td *TextDisplay) HandleEvent(event Event) error

HandleEvent handles events (text display components typically don't handle events)

func (*TextDisplay) Render

func (td *TextDisplay) Render(ctx context.Context) string

Render renders component

func (*TextDisplay) SetAlign

func (td *TextDisplay) SetAlign(align string) *TextDisplay

SetAlign sets alignment

func (*TextDisplay) SetBorder

func (td *TextDisplay) SetBorder(border, rounded bool) *TextDisplay

SetBorder sets border

func (*TextDisplay) SetMarkdown

func (td *TextDisplay) SetMarkdown(markdown bool) *TextDisplay

SetMarkdown sets Markdown rendering

func (*TextDisplay) SetMaxWidth

func (td *TextDisplay) SetMaxWidth(maxWidth int) *TextDisplay

SetMaxWidth sets maximum width (simplified version for method chaining)

func (*TextDisplay) SetPadding

func (td *TextDisplay) SetPadding(padding int) *TextDisplay

SetPadding sets padding

func (*TextDisplay) SetPrefix

func (td *TextDisplay) SetPrefix(prefix string) *TextDisplay

SetPrefix sets prefix

func (*TextDisplay) SetPrefixStyle

func (td *TextDisplay) SetPrefixStyle(style Style) *TextDisplay

SetPrefixStyle sets prefix style

func (*TextDisplay) SetState

func (td *TextDisplay) SetState(state State)

SetState sets state

func (*TextDisplay) SetStyle

func (td *TextDisplay) SetStyle(style Style) *TextDisplay

SetStyle sets text style

func (*TextDisplay) SetSuffix

func (td *TextDisplay) SetSuffix(suffix string) *TextDisplay

SetSuffix sets suffix

func (*TextDisplay) SetText

func (td *TextDisplay) SetText(text string) *TextDisplay

SetText sets display text

func (*TextDisplay) SetTheme

func (td *TextDisplay) SetTheme(theme Theme)

SetTheme sets theme

func (*TextDisplay) SetWidth

func (td *TextDisplay) SetWidth(maxWidth, minWidth int) *TextDisplay

SetWidth sets width

func (*TextDisplay) SetWordWrap

func (td *TextDisplay) SetWordWrap(wordWrap bool) *TextDisplay

SetWordWrap sets automatic word wrapping

func (*TextDisplay) State

func (td *TextDisplay) State() State

State gets state

type TextInput

type TextInput struct {
	// contains filtered or unexported fields
}

TextInput represents a text input component

func NewTextInput

func NewTextInput() *TextInput

NewTextInput creates a new text input component

func (*TextInput) Blur

func (t *TextInput) Blur()

Blur removes focus from the input

func (*TextInput) Focus

func (t *TextInput) Focus()

Focus gives focus to the input

func (*TextInput) GetValue

func (t *TextInput) GetValue() string

GetValue returns the input value

func (*TextInput) HandleEvent

func (t *TextInput) HandleEvent(event Event) error

HandleEvent handles events

func (*TextInput) OnCancel

func (t *TextInput) OnCancel(callback func()) *TextInput

OnCancel sets the cancel callback

func (*TextInput) OnChange

func (t *TextInput) OnChange(callback func(string)) *TextInput

OnChange sets the value change callback

func (*TextInput) OnSubmit

func (t *TextInput) OnSubmit(callback func(string)) *TextInput

OnSubmit sets the submit callback

func (*TextInput) Render

func (t *TextInput) Render(ctx context.Context) string

Render renders the input component

func (*TextInput) SetMaxLength

func (t *TextInput) SetMaxLength(maxLength int) *TextInput

SetMaxLength sets the maximum input length

func (*TextInput) SetMessage

func (t *TextInput) SetMessage(message string) *TextInput

SetMessage sets the prompt message

func (*TextInput) SetMultiline

func (t *TextInput) SetMultiline(multiline bool, height int) *TextInput

SetMultiline sets multiline mode

func (*TextInput) SetPlaceholder

func (t *TextInput) SetPlaceholder(placeholder string) *TextInput

SetPlaceholder sets the placeholder text

func (*TextInput) SetState

func (t *TextInput) SetState(state State)

SetState sets the state

func (*TextInput) SetTheme

func (t *TextInput) SetTheme(theme Theme)

SetTheme sets the theme

func (*TextInput) SetValidator

func (t *TextInput) SetValidator(validator ValidatorFunc[string]) *TextInput

SetValidator sets the input validator

func (*TextInput) SetValue

func (t *TextInput) SetValue(value string) *TextInput

SetValue sets the input value

func (*TextInput) SetWidth

func (t *TextInput) SetWidth(width int) *TextInput

SetWidth sets the input width

func (*TextInput) State

func (t *TextInput) State() State

State returns the current state

type TextUtils

type TextUtils struct{}

TextUtils provides text processing utility functions

func (TextUtils) AlignText

func (TextUtils) AlignText(text string, width int, alignment string) string

AlignText aligns text

func (TextUtils) IndentText

func (TextUtils) IndentText(text string, indent int) string

IndentText indents text

func (TextUtils) WordWrap

func (TextUtils) WordWrap(text string, width int) []string

WordWrap performs intelligent text wrapping

type Theme

type Theme interface {
	Name() string
	Primary() Style
	Secondary() Style
	Success() Style
	Error() Style
	Warning() Style
	Info() Style
	Background() Style
	Foreground() Style
	Border() Style
	Focused() Style
}

Theme defines the theming interface

func GetThemeByName

func GetThemeByName(name string) Theme

func NewDefaultTheme

func NewDefaultTheme() Theme

NewDefaultTheme creates a default theme

func NewDraculaTheme

func NewDraculaTheme() Theme

NewDraculaTheme creates a Dracula theme

func NewGitHubTheme

func NewGitHubTheme() Theme

NewGitHubTheme creates a GitHub theme

func NewModernTheme

func NewModernTheme() Theme

NewModernTheme creates a modern theme

func NewVSCodeTheme

func NewVSCodeTheme() Theme

NewVSCodeTheme creates a VSCode theme

type VSCodeTheme

type VSCodeTheme struct {
	// contains filtered or unexported fields
}

VSCodeTheme represents a VSCode dark theme

func (*VSCodeTheme) Background

func (t *VSCodeTheme) Background() Style

func (*VSCodeTheme) Border

func (t *VSCodeTheme) Border() Style

func (*VSCodeTheme) Error

func (t *VSCodeTheme) Error() Style

func (*VSCodeTheme) Focused

func (t *VSCodeTheme) Focused() Style

func (*VSCodeTheme) Foreground

func (t *VSCodeTheme) Foreground() Style

func (*VSCodeTheme) Info

func (t *VSCodeTheme) Info() Style

func (*VSCodeTheme) Name

func (t *VSCodeTheme) Name() string

func (*VSCodeTheme) Primary

func (t *VSCodeTheme) Primary() Style

func (*VSCodeTheme) Secondary

func (t *VSCodeTheme) Secondary() Style

func (*VSCodeTheme) Success

func (t *VSCodeTheme) Success() Style

func (*VSCodeTheme) Warning

func (t *VSCodeTheme) Warning() Style

type VStack

type VStack struct {
	// contains filtered or unexported fields
}

VStack vertical stack layout

func NewVStack

func NewVStack() *VStack

NewVStack creates vertical stack layout

func (*VStack) AddChild

func (v *VStack) AddChild(child Component) *VStack

AddChild adds child component

func (*VStack) HandleEvent

func (v *VStack) HandleEvent(event Event) error

HandleEvent handles events

func (*VStack) Render

func (v *VStack) Render(ctx context.Context) string

Render renders component

func (*VStack) SetAlignment

func (v *VStack) SetAlignment(alignment string) *VStack

SetAlignment sets alignment

func (*VStack) SetSpacing

func (v *VStack) SetSpacing(spacing int) *VStack

SetSpacing sets spacing

func (*VStack) SetState

func (v *VStack) SetState(state State)

SetState sets state

func (*VStack) SetTheme

func (v *VStack) SetTheme(theme Theme)

SetTheme sets theme

func (*VStack) SetWidth

func (v *VStack) SetWidth(width int) *VStack

SetWidth sets width

func (*VStack) State

func (v *VStack) State() State

State gets state

type ValidatorFunc

type ValidatorFunc[T any] func(value T) error

type Writer

type Writer interface {
	Write(p []byte) (n int, err error)
	WriteString(s string) (n int, err error)
	Clear() error
	MoveCursor(x, y int) error
	HideCursor() error
	ShowCursor() error
}

Writer defines output writing interface

Jump to

Keyboard shortcuts

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