terminus

package
v0.0.0-...-41e4b49 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	NewStyle = style.New

	// Color constructors
	ColorFromString = style.ColorFromString
	ANSI256         = style.ANSI256
	RGB             = style.RGB

	// Predefined colors
	Black         = style.Black
	Red           = style.Red
	Green         = style.Green
	Yellow        = style.Yellow
	Blue          = style.Blue
	Magenta       = style.Magenta
	Cyan          = style.Cyan
	White         = style.White
	BrightBlack   = style.BrightBlack
	BrightRed     = style.BrightRed
	BrightGreen   = style.BrightGreen
	BrightYellow  = style.BrightYellow
	BrightBlue    = style.BrightBlue
	BrightMagenta = style.BrightMagenta
	BrightCyan    = style.BrightCyan
	BrightWhite   = style.BrightWhite
)

Style constructors

Functions

func Cancel

func Cancel(id string)

Cancel cancels a command by ID

func CancelAll

func CancelAll()

CancelAll cancels all registered commands

Types

type ANSIParser

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

ANSIParser parses ANSI escape sequences from a string

func NewANSIParser

func NewANSIParser(input string) *ANSIParser

NewANSIParser creates a new ANSI parser

func (*ANSIParser) Next

func (p *ANSIParser) Next() (rune, Style, bool)

Next returns the next rune and its style

type CancellableCmd

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

CancellableCmd represents a command that can be cancelled

type CancellationRegistry

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

CancellationRegistry manages cancellable commands

func NewCancellationRegistry

func NewCancellationRegistry() *CancellationRegistry

NewCancellationRegistry creates a new cancellation registry

func (*CancellationRegistry) Cancel

func (r *CancellationRegistry) Cancel(id string)

Cancel cancels a command by ID

func (*CancellationRegistry) CancelAll

func (r *CancellationRegistry) CancelAll()

CancelAll cancels all registered commands

func (*CancellationRegistry) IsActive

func (r *CancellationRegistry) IsActive(id string) bool

IsActive checks if a command with the given ID is currently running

func (*CancellationRegistry) WithCancel

func (r *CancellationRegistry) WithCancel(id string, cmd func(ctx context.Context) Msg) Cmd

WithCancel creates a cancellable command with a unique ID using this registry

type Cell

type Cell struct {
	Rune  rune
	Style Style
}

Cell represents a single character cell in the terminal

type ClientMessage

type ClientMessage struct {
	Type string      `json:"type"`
	Data interface{} `json:"data"`
}

ClientMessage represents a message from the client

type Cmd

type Cmd func() Msg

Cmd represents a command that performs side effects and returns a message

var Quit Cmd = func() Msg {
	return QuitMsg{}
}

Quit is a special command that signals the application should terminate

func Batch

func Batch(cmds ...Cmd) Cmd

Batch performs a list of commands in parallel and returns immediately

func Debounce

func Debounce(id string, delay time.Duration, cmd Cmd) Cmd

Debounce creates a command that will only execute after a period of inactivity

func Delete

func Delete(url string) Cmd

Delete performs a DELETE request

func Every

func Every(d time.Duration, fn func(time.Time) Msg) Cmd

Every returns a command that sends a message at regular intervals Note: This command runs indefinitely and should be used with WithCancel

func Get

func Get(url string) Cmd

Get performs a GET request

func GetWithTag

func GetWithTag(url string, tag string) Cmd

GetWithTag performs a GET request with a tag

func HTTPRequest

func HTTPRequest(method HTTPMethod, url string, body io.Reader) Cmd

HTTPRequest performs an HTTP request and returns the result as a message

func HTTPRequestWithContext

func HTTPRequestWithContext(ctx context.Context, method HTTPMethod, url string, body io.Reader, headers map[string]string, tag string) Cmd

HTTPRequestWithContext performs an HTTP request with a context for cancellation

func HTTPRequestWithHeaders

func HTTPRequestWithHeaders(method HTTPMethod, url string, body io.Reader, headers map[string]string) Cmd

HTTPRequestWithHeaders performs an HTTP request with custom headers

func HTTPRequestWithTag

func HTTPRequestWithTag(method HTTPMethod, url string, body io.Reader, tag string) Cmd

HTTPRequestWithTag performs an HTTP request with a tag for identification

func Interval

func Interval(id string, duration time.Duration, fn func(time.Time) Msg) Cmd

Interval creates a cancellable command that sends messages at regular intervals

func JSONRequest

func JSONRequest(method HTTPMethod, url string, data interface{}) Cmd

JSONRequest performs an HTTP request with JSON encoding/decoding

func JSONRequestWithTag

func JSONRequestWithTag(method HTTPMethod, url string, data interface{}, tag string) Cmd

JSONRequestWithTag performs an HTTP request with JSON encoding/decoding and a tag

func Parallel

func Parallel(cmds ...Cmd) Cmd

Parallel performs commands in parallel and waits for all to complete

func Post

func Post(url string, data interface{}) Cmd

Post performs a POST request with JSON data

func PostWithTag

func PostWithTag(url string, data interface{}, tag string) Cmd

PostWithTag performs a POST request with JSON data and a tag

func Put

func Put(url string, data interface{}) Cmd

Put performs a PUT request with JSON data

func Sequence

func Sequence(cmds ...Cmd) Cmd

Sequence performs commands one after another, waiting for each to complete

func Throttle

func Throttle(id string, minInterval time.Duration, cmd Cmd) Cmd

func Tick

func Tick(d time.Duration, fn func(time.Time) Msg) Cmd

Tick returns a command that will wait for the given duration, then return a TickMsg

func Timeout

func Timeout(d time.Duration, cmd Cmd) Cmd

Timeout creates a command that will be automatically cancelled after a duration

func WithCancel

func WithCancel(id string, cmd func(ctx context.Context) Msg) Cmd

WithCancel creates a cancellable command with a unique ID

type Color

type Color = style.Color

Style exports

type CommandProcessor

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

CommandProcessor manages concurrent execution of commands

func NewCommandProcessor

func NewCommandProcessor(workerCount int, msgSender func(Msg)) *CommandProcessor

NewCommandProcessor creates a new command processor with the specified number of workers

func (*CommandProcessor) Execute

func (p *CommandProcessor) Execute(cmd Cmd)

Execute queues a command for execution

func (*CommandProcessor) Start

func (p *CommandProcessor) Start()

Start begins processing commands

func (*CommandProcessor) Stop

func (p *CommandProcessor) Stop()

Stop gracefully shuts down the processor

type Component

type Component interface {
	// Init is called once when the component is first created
	// It returns an optional command to execute
	Init() Cmd

	// Update handles incoming messages and updates the component state
	// It returns the new component state and an optional command
	Update(msg Msg) (Component, Cmd)

	// View renders the component's current state as a string
	View() string
}

Component is the core interface that all UI components must implement

type DiffOp

type DiffOp struct {
	Type DiffOpType
	Data interface{}
}

DiffOp represents a diff operation

type DiffOpType

type DiffOpType string

DiffOpType represents the type of diff operation

const (
	DiffOpClear      DiffOpType = "clear"
	DiffOpSetCell    DiffOpType = "setCell"
	DiffOpUpdateLine DiffOpType = "updateLine"
	DiffOpScrollUp   DiffOpType = "scrollUp"
	DiffOpScrollDown DiffOpType = "scrollDown"
)

type Differ

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

Differ computes differences between two screens

func NewDiffer

func NewDiffer() *Differ

NewDiffer creates a new differ

func (*Differ) Diff

func (d *Differ) Diff(oldScreen, newScreen *Screen) []DiffOp

Diff computes the differences between two screens

type Engine

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

Engine manages the MVU (Model-View-Update) lifecycle for a component

func NewEngine

func NewEngine(component Component) *Engine

NewEngine creates a new MVU engine with the given component

func (*Engine) SendMessage

func (e *Engine) SendMessage(msg Msg)

SendMessage sends a message to the component

func (*Engine) SetQuitCallback

func (e *Engine) SetQuitCallback(fn func())

SetQuitCallback sets the function to call when the engine quits

func (*Engine) SetRenderCallback

func (e *Engine) SetRenderCallback(fn func(view string))

SetRenderCallback sets the function to call when a new view is rendered

func (*Engine) Start

func (e *Engine) Start() error

Start begins the MVU loop

func (*Engine) Stop

func (e *Engine) Stop()

Stop gracefully shuts down the engine

type HTTPMethod

type HTTPMethod string

HTTPMethod represents an HTTP method

const (
	GET    HTTPMethod = "GET"
	POST   HTTPMethod = "POST"
	PUT    HTTPMethod = "PUT"
	DELETE HTTPMethod = "DELETE"
	PATCH  HTTPMethod = "PATCH"
)

type HTTPRequestMsg

type HTTPRequestMsg struct {
	Response *http.Response
	Body     []byte
	Error    error
	Tag      string // Optional tag to identify the request
}

HTTPRequestMsg is sent when an HTTP request completes

func (HTTPRequestMsg) IsHTTPError

func (msg HTTPRequestMsg) IsHTTPError() bool

IsHTTPError checks if the HTTP response indicates an error

func (HTTPRequestMsg) IsNetworkError

func (msg HTTPRequestMsg) IsNetworkError() bool

IsNetworkError checks if the request failed due to a network error

func (HTTPRequestMsg) JSONBody

func (msg HTTPRequestMsg) JSONBody(v interface{}) error

JSONBody attempts to unmarshal the response body as JSON

func (HTTPRequestMsg) StatusCode

func (msg HTTPRequestMsg) StatusCode() int

StatusCode returns the HTTP status code, or 0 if no response

func (HTTPRequestMsg) String

func (msg HTTPRequestMsg) String() string

String returns the response body as a string

type KeyMsg

type KeyMsg struct {
	Type  KeyType
	Runes []rune // For KeyRunes type
	Alt   bool   // Alt modifier
	Ctrl  bool   // Ctrl modifier
	Shift bool   // Shift modifier
}

KeyMsg represents a keyboard input message

func (KeyMsg) String

func (k KeyMsg) String() string

String returns a human-readable representation of the key message

type KeyType

type KeyType int

KeyType represents different types of keyboard input

const (
	// KeyRunes represents character input
	KeyRunes KeyType = iota
	// KeyEnter represents the Enter key
	KeyEnter
	// KeySpace represents the Space key
	KeySpace
	// KeyBackspace represents the Backspace key
	KeyBackspace
	// KeyDelete represents the Delete key
	KeyDelete
	// KeyTab represents the Tab key
	KeyTab
	// KeyEsc represents the Escape key
	KeyEsc
	// KeyUp represents the Up arrow key
	KeyUp
	// KeyDown represents the Down arrow key
	KeyDown
	// KeyLeft represents the Left arrow key
	KeyLeft
	// KeyRight represents the Right arrow key
	KeyRight
	// KeyHome represents the Home key
	KeyHome
	// KeyEnd represents the End key
	KeyEnd
	// KeyPgUp represents the Page Up key
	KeyPgUp
	// KeyPgDown represents the Page Down key
	KeyPgDown
	// KeyF1 through KeyF12 represent function keys
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
	// KeyCtrlC represents Ctrl+C
	KeyCtrlC
	// KeyCtrlD represents Ctrl+D
	KeyCtrlD
	// KeyCtrlR represents Ctrl+R
	KeyCtrlR
	// KeyCtrlS represents Ctrl+S
	KeyCtrlS
	// KeyCtrlZ represents Ctrl+Z
	KeyCtrlZ
)

type Line

type Line []Cell

Line represents a line of cells

type Msg

type Msg interface{}

Msg is a marker interface for messages that can be sent to components

type Program

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

Program is the main entry point for a TerminusGo application

func NewProgram

func NewProgram(rootComponentFactory func() Component, opts ...ProgramOption) *Program

NewProgram creates a new TerminusGo program

func (*Program) Start

func (p *Program) Start() error

Start starts the TerminusGo program

func (*Program) Stop

func (p *Program) Stop() error

Stop gracefully shuts down the program

func (*Program) Wait

func (p *Program) Wait()

Wait blocks until the program is stopped

type ProgramOption

type ProgramOption func(*Program)

ProgramOption is a function that configures a Program

func WithAddress

func WithAddress(addr string) ProgramOption

WithAddress configures the server address

func WithStaticFiles

func WithStaticFiles(fs embed.FS, path string) ProgramOption

WithStaticFiles configures the program to serve static files from an embedded filesystem

type QuitMsg

type QuitMsg struct{}

QuitMsg is a message type for signaling application quit

type Screen

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

Screen represents the virtual terminal screen

func NewScreen

func NewScreen(width, height int) *Screen

NewScreen creates a new virtual screen

func (*Screen) Clear

func (s *Screen) Clear()

Clear clears the screen

func (*Screen) GetCell

func (s *Screen) GetCell(x, y int) Cell

GetCell gets the cell at the given position

func (*Screen) RenderFromString

func (s *Screen) RenderFromString(content string)

RenderFromString renders a string to the screen, handling ANSI codes

func (*Screen) SetCell

func (s *Screen) SetCell(x, y int, r rune, style Style)

SetCell sets a cell at the given position

func (*Screen) ToString

func (s *Screen) ToString() string

ToString converts the screen to a plain string (for testing)

type ScreenDiffer

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

ScreenDiffer manages stateful diffing between screen updates

func NewScreenDiffer

func NewScreenDiffer(width, height int) *ScreenDiffer

NewScreenDiffer creates a new screen differ

func (*ScreenDiffer) Reset

func (sd *ScreenDiffer) Reset()

Reset clears the differ state

func (*ScreenDiffer) Resize

func (sd *ScreenDiffer) Resize(width, height int)

Resize updates the screen dimensions

func (*ScreenDiffer) Update

func (sd *ScreenDiffer) Update(content string) []DiffOp

Update computes diff operations for a new screen state

type ServerMessage

type ServerMessage struct {
	Type string                 `json:"type"`
	Data map[string]interface{} `json:"data"`
}

ServerMessage represents a message to the client

type Session

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

Session represents a single connected client

func NewSession

func NewSession(id string, conn *websocket.Conn, component Component) *Session

NewSession creates a new session

func (*Session) Close

func (s *Session) Close()

Close closes the session

func (*Session) ID

func (s *Session) ID() string

ID returns the session ID

func (*Session) Run

func (s *Session) Run(ctx context.Context)

Run starts the session

type SessionManager

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

SessionManager manages active sessions

func NewSessionManager

func NewSessionManager() *SessionManager

NewSessionManager creates a new session manager

func (*SessionManager) CloseAll

func (sm *SessionManager) CloseAll()

CloseAll closes all sessions

func (*SessionManager) Count

func (sm *SessionManager) Count() int

Count returns the number of active sessions

func (*SessionManager) CreateSession

func (sm *SessionManager) CreateSession(conn *websocket.Conn, component Component) *Session

CreateSession creates a new session

func (*SessionManager) GetSession

func (sm *SessionManager) GetSession(id string) *Session

GetSession retrieves a session by ID

func (*SessionManager) RemoveSession

func (sm *SessionManager) RemoveSession(id string)

RemoveSession removes a session

type SetCellOp

type SetCellOp struct {
	X     int    `json:"x"`
	Y     int    `json:"y"`
	Rune  string `json:"rune"`
	Style string `json:"style,omitempty"`
}

SetCellOp represents a single cell update

type Style

type Style = style.Style

Style exports

type TickMsg

type TickMsg interface {
	Msg
	Time() time.Time
}

TickMsg returns the time at which the tick occurred

type TimeoutMsg

type TimeoutMsg struct {
	Duration time.Duration
}

TimeoutMsg is sent when a command times out

type UpdateLineOp

type UpdateLineOp struct {
	Y       int    `json:"y"`
	Content string `json:"content"`
}

UpdateLineOp represents a full line update

type WindowSizeMsg

type WindowSizeMsg struct {
	Width  int
	Height int
}

WindowSizeMsg is sent when the terminal window is resized

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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