mofu

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 26 Imported by: 0

README

MOFU

The Reactive Terminal Application Runtime

Go License Version Tests Gadgets Examples


Quick Start

go get github.com/xanstomper/mofu
package main

import (
    "fmt"
    "github.com/xanstomper/mofu"
)

func main() {
    mofu.Run(&counter{})
}

type counter struct {
    mofu.Minimal
    n int
}

func (c *counter) Render(ctx *mofu.RenderContext) {
    ctx.Renderer.WriteString(
        fmt.Sprintf("Count: %d  (↑/↓ to change, q to quit)", c.n),
        0, 0, mofu.Hex("cdd6f4"), mofu.ColorBlack, 0,
    )
}

func (c *counter) HandleEvent(e mofu.Event) mofu.Cmd {
    if e.Type != mofu.EventKeyPress { return nil }
    ke := e.Data.(mofu.KeyEvent)
    switch {
    case ke.Key == mofu.KeyUp: c.n++
    case ke.Key == mofu.KeyDown: c.n--
    case ke.Key == mofu.KeyEsc: return mofu.QuitCmd()
    }
    return nil
}
go run main.go

Examples (25)

App Run Description
counter cd examples/counter && go run . Minimal counter — starter template
dashboard cd examples/dashboard && go run . Multi-panel system dashboard
chat cd examples/chat && go run . Chat interface with messages
email cd examples/email && go run . Email client with folders, preview
filemanager cd examples/filemanager && go run . Directory browser with tree navigation
form cd examples/form && go run . Registration form with validation
settings cd examples/settings && go run . Settings panel with toggles
logviewer cd examples/logviewer && go run . Log filtering and search
logmonitor cd examples/logmonitor && go run . Real-time log file watcher
wizard cd examples/wizard && go run . Setup wizard with steps
monitor cd examples/monitor && go run . System metrics with sparklines
gitui cd examples/gitui && go run . Git interface (branches, diff)
dockerui cd examples/dockerui && go run . Docker container dashboard
kanban cd examples/kanban && go run . Kanban board
calculator cd examples/calculator && go run . Calculator with input
taskmanager cd examples/taskmanager && go run . Task CRUD with filter/sort
markdown cd examples/markdown && go run . Markdown viewer with scroll
csvviewer cd examples/csvviewer && go run . CSV browser with sort/filter
stocktracker cd examples/stocktracker && go run . Stock tracker with sparklines
musicplayer cd examples/musicplayer && go run . Music player with playlists
notepad cd examples/notepad && go run . Multi-tab text editor
pomodoro cd examples/pomodoro && go run . Pomodoro timer with sessions
budget cd examples/budget && go run . Budget tracker with categories
aiworkflow cd examples/aiworkflow && go run . AI agent workflow display

Why MOFU?

MOFU is not another TUI framework. It's a reactive terminal runtime built for AI agents and streaming data.

vs Bubble Tea / Ratatui / OpenTUI

Feature MOFU Bubble Tea Ratatui OpenTUI
Architecture Reactive graph + diff Elm loop + full rebuild Immediate mode React-like
Render model Cell-level differential Full string rebuild Full buffer copy Virtual DOM
Allocations/frame 0 (hot path) N (string concat) N (Vec growth) N
Input latency <1ms (batched) Per-keystroke Per-keystroke Per-keystroke
Streaming Built-in SSE + ring buffer Manual None Manual
AI agent display Native (agent/) None None Basic
Gadgets 112 production-ready 0 (manual) 0 (manual) 0
Virtual scroll O(1) for millions of lines None Optional None
Multi-agent Tab orchestration None None None
API streaming OpenAI/Anthropic/Ollama None None None
Cost tracking Built-in token/cost None None None
Markdown Terminal-native renderer None None None

Performance

RingBuffer write 1KB:    90ns   0 allocs
RingBuffer read 1KB:    126ns   0 allocs
VirtualScroll scroll:    70ns   0 allocs
VirtualScroll append:   349ns   0 allocs
StreamingBuffer:        123ns   0 allocs
SSEParser (1 event):   3.3µs   4 allocs
DiffRenderer:           cell-level differential — only changed cells written to terminal

Architecture

┌─────────────────────────────────────────────────┐
│                  MOFU Runtime                    │
│  ┌──────────┐  ┌──────────┐  ┌──────────────┐  │
│  │  Kernel   │  │  State   │  │    Render     │  │
│  │ (input→   │  │  Graph   │  │  (diff+flush) │  │
│  │  state→   │  │ (dirty   │  │  cell-level   │  │
│  │  render)  │  │  DAG)    │  │  differential │  │
│  └──────────┘  └──────────┘  └──────────────┘  │
├─────────────────────────────────────────────────┤
│              Package Ecosystem                   │
│  gadgets/   → 112 UI components                  │
│  widgets/   → 18 basic UI primitives             │
│  agent/     → AI workflow display                │
│  cuddles/   → Semantic themes                    │
│  meow/      → Schema-driven forms                │
│  render/    → Diff renderer, scene buffer        │
│  state/     → Reactive state graph               │
│  kernel/    → Event loop, input parsing          │
└─────────────────────────────────────────────────┘

Packages

Package Description
mofu Core runtime — kernel, state graph, renderer, input, events, layout
agent AI agent display — API streaming, tool calls, virtual scroll, SSE parser, multi-agent orchestration
gadgets 112 production-ready UI components — tables, charts, forms, monitors, dev tools
widgets 18 basic UI primitives — Input, Button, List, Table, Select, Checkbox, Modal, Tabs, Toast, Tooltip, Tree, Viewport
cuddles Semantic themes — Mochi, Catppuccin, Tokyo Night with dark/light variants
meow Schema-driven forms with validators and computed fields
kernel Event loop, input parsing (CSI, SS3, mouse SGR, Ctrl+key)
state Reactive state graph with dirty-bit DAG propagation
render Diff renderer with preallocated framebuffer and SGR cache
message Type-safe message bus with pub/sub
effect Async effect system for plugin/IO dispatch
ascii ASCII art scene rendering

Gadgets (112)

All gadgets have real functionality — mutex-protected state, data manipulation, event handling, styled rendering.

Data & Visualization (16) HeatMap, Sparkline, ProgressBar, Donut, Gauge, Timer, PieChart, MiniMap, BoxPlot, RadarChart, WaterfallChart, FunnelChart, TreemapChart, HeatCalendar, DotPlot, Candlestick

Dev Tools (14) APIClient, ProcessViewer, PortScanner, GitBranches, GitLog, FileExplorer, DiffViewer, HexViewer, CodeBlock, EnvConfig, CronScheduler, AICodeReview, DependencyGraph, JSONViewer

System (10) SystemMonitor, DiskUsage, NetworkStats, ServiceHealth, IncidentTracker, DeploymentTracker, AuditLog, LogAggregator, ResourceMonitor, AlertBanner

Interactive (9) CRUDTable, SearchBox, DropDown, QueryBuilder, FormField, FeatureFlags, ToolPanel, PipelineRunner, DBSchema

Display (15) MarkdownPreview, SyntaxHighlighter, StatusPage, KeyValueEditor, LogFilter, Accordion, Tabs, Breadcrumb, Badge, Toast, NotificationPanel, WordCounter, TextTransform, ProgressBarSteps, ProgressBarAnimated

AI/Agent (10) DiffViewerPro, JSONViewer, StatusPage, MarkdownPreview, AICodeReview, DependencyGraph, MetricGauge, FileWatcher, StreamDisplay, AgentDashboard

Terminal Tools (10) TerminalOutput, ProgressBarDual, TimelineCompact, KeyValueEditor, LogFilter, AsciiTable, DonutChart, GitLog, SSHSession, NetworkPing

Text & Input (6) WordCounter, TextTransform, GrepViewer, CRUDTable, ProgressBarSteps, ProgressBarAnimated

Agent Package

Built for AI agent workflows — streaming, tool calls, cost tracking, multi-agent orchestration.

// Create an agent connected to any OpenAI-compatible API
a := agent.NewInstantAgent("my-agent", apiURL, apiKey, model)
a.SetSystemPrompt("You are a helpful assistant.")

// Stream responses token-by-token
a.OnToken(func(token string) {
    // Render instantly to terminal
})

// Send messages
a.Send("Explain this code")

// Use tools
a.RegisterTool("bash", func(input string) (string, error) {
    return exec.Command("bash", "-c", input).Output()
})

Components:

Component Purpose
Agent Core agent state machine with tool calls, streaming, thinking
InstantAgent Production agent with live API streaming
APIStream HTTP client for OpenAI/Anthropic/Ollama SSE endpoints
ToolPanel Side panel showing active/completed tool calls
CostBar Token usage and cost tracking bar
VirtualScroll O(1) scroll through millions of log lines
MarkdownRenderer Terminal-native markdown (headers, code blocks, lists)
Orchestrator Multi-agent tab display
EventTimeline Chronological event log with filtering
AgentDashboard Full-screen monitoring dashboard
WorkflowView Complete multi-panel layout
StreamDisplay Instant terminal rendering of streamed tokens

Widgets (18)

Simple, focused UI primitives for building interactive TUIs:

Widget Description
Input Text input with cursor, validator, password mode
Button Clickable button with label and callback
List Navigable list with items
Table Data table with columns and rows
Select Dropdown select with options
Checkbox Toggle checkbox
Modal Modal dialog overlay
Tabs Tab bar with active state
Toast Temporary notification popup
Tooltip Hover tooltip
Tree Hierarchical tree view
Viewport Scrollable viewport
Text Styled text display
ProgressBar Progress indicator
Menu Menu with items

Documentation

Guide Description
Architecture MOFU's reactive graph architecture
Getting Started First steps tutorial
Styling Colors, themes, and attributes
Gadgets Using the 112 gadget library
Forms Building forms with Meow
Testing Testing MOFU applications
Performance Optimization guide
Migration Migrating from Bubble Tea

Tutorials

Tutorial Source
Log Monitor Build a real-time log monitor from scratch
AI Agent Display Connect to an API and stream responses
Data Dashboard Compose gadgets into a live dashboard

License

MIT

Documentation

Index

Constants

View Source
const EllipsisRune = '…'

EllipsisRune is the Unicode ellipsis character.

Variables

View Source
var (
	ColorBlack        = ANSI(0)
	ColorRed          = ANSI(1)
	ColorGreen        = ANSI(2)
	ColorYellow       = ANSI(3)
	ColorBlue         = ANSI(4)
	ColorMagenta      = ANSI(5)
	ColorCyan         = ANSI(6)
	ColorWhite        = ANSI(7)
	ColorBrightBlack  = ANSI(8)
	ColorBrightRed    = ANSI(9)
	ColorBrightGreen  = ANSI(10)
	ColorBrightYellow = ANSI(11)
	ColorBrightBlue   = ANSI(12)
	ColorBrightCyan   = ANSI(14)
	ColorBrightWhite  = ANSI(15)
)

Common ANSI color codes

View Source
var (
	ColorTransparent = Color{}
	ColorBlackTrue   = RGB(0, 0, 0)
	ColorWhiteTrue   = RGB(255, 255, 255)
	ColorGray        = RGB(128, 128, 128)
)

Common true colors

View Source
var (
	ErrProgramPanic  = fmt.Errorf("mofu: program experienced a panic")
	ErrProgramKilled = fmt.Errorf("mofu: program was killed")
	ErrInterrupted   = fmt.Errorf("mofu: program was interrupted")
)
View Source
var (
	// BorderNone is no border.
	BorderNone = BorderStyle{}
	// BorderHidden is a hidden border (same as none).
	BorderHidden = BorderStyle{}
	// BorderNormal is a standard box border.
	BorderNormal = BorderStyle{
		Top: '─', Bottom: '─', Left: '│', Right: '│',
		TopLeft: '┌', TopRight: '┐', BottomLeft: '└', BottomRight: '┘',
	}
	// BorderRounded is a rounded corner border.
	BorderRounded = BorderStyle{
		Top: '─', Bottom: '─', Left: '│', Right: '│',
		TopLeft: '╭', TopRight: '╮', BottomLeft: '╰', BottomRight: '╯',
	}
	// BorderThick is a thick border.
	BorderThick = BorderStyle{
		Top: '━', Bottom: '━', Left: '┃', Right: '┃',
		TopLeft: '┏', TopRight: '┓', BottomLeft: '┗', BottomRight: '┛',
	}
	// BorderDouble is a double-line border.
	BorderDouble = BorderStyle{
		Top: '═', Bottom: '═', Left: '║', Right: '║',
		TopLeft: '╔', TopRight: '╗', BottomLeft: '╚', BottomRight: '╝',
	}
)

Functions

func AlignLine

func AlignLine(text string, width int, align TextAlign) string

AlignLine returns text aligned per TextAlign rule within width.

func Analogous

func Analogous(c Color, angle float64) (Color, Color)

func AnimateOpacity

func AnimateOpacity(animator *Animator, from, to float64, duration time.Duration, setter func(float64)) uint64

AnimateOpacity creates a fade animation (0-1 range).

func AnimateValue

func AnimateValue(animator *Animator, from, to float64, duration time.Duration, easing EasingFn, setter func(float64)) uint64

AnimateValue creates a tween that updates a setter function each frame.

func CharWrap

func CharWrap(text string, maxWidth int) []string

CharWrap wraps character-by-character (CJK-safe).

func ComputeLayout

func ComputeLayout(node Node, bounds Rect)

func ContrastRatio

func ContrastRatio(a, b Color) float64

func DiffProps

func DiffProps(old, new map[string]any) map[string]any

DiffProps compares two property maps and returns changes.

func DisableMouse

func DisableMouse() string

func EaseInBack

func EaseInBack(t float64) float64

EaseInBack accelerates pulling back then shooting forward.

func EaseInBounce

func EaseInBounce(t float64) float64

EaseInBounce accelerates with a bounce effect.

func EaseInCubic

func EaseInCubic(t float64) float64

EaseInCubic accelerates from zero velocity.

func EaseInElastic

func EaseInElastic(t float64) float64

EaseInElastic accelerates with an elastic snap.

func EaseInExpo

func EaseInExpo(t float64) float64

EaseInExpo accelerates exponentially.

func EaseInOutBounce

func EaseInOutBounce(t float64) float64

EaseInOutBounce bounce effect in both directions.

func EaseInOutCubic

func EaseInOutCubic(t float64) float64

EaseInOutCubic acceleration until halfway, then deceleration.

func EaseInOutExpo

func EaseInOutExpo(t float64) float64

EaseInOutExpo acceleration until halfway, then deceleration.

func EaseInOutQuad

func EaseInOutQuad(t float64) float64

EaseInOutQuad acceleration until halfway, then deceleration.

func EaseInQuad

func EaseInQuad(t float64) float64

EaseInQuad accelerates from zero velocity.

func EaseLinear

func EaseLinear(t float64) float64

EaseLinear is the default easing — no acceleration.

func EaseOutBack

func EaseOutBack(t float64) float64

EaseOutBack decelerates overshooting then settling.

func EaseOutBounce

func EaseOutBounce(t float64) float64

EaseOutBounce decelerates with a bounce effect.

func EaseOutCubic

func EaseOutCubic(t float64) float64

EaseOutCubic decelerates to zero velocity.

func EaseOutElastic

func EaseOutElastic(t float64) float64

EaseOutElastic decelerates with an elastic snap.

func EaseOutExpo

func EaseOutExpo(t float64) float64

EaseOutExpo decelerates exponentially.

func EaseOutQuad

func EaseOutQuad(t float64) float64

EaseOutQuad decelerates to zero velocity.

func EnableMouse

func EnableMouse(mode MouseMode) string

func FormatTable

func FormatTable(headers []string, rows [][]string, cols []ColumnAlign) []string

FormatTable formats rows into aligned columns.

func IsColorBlindSafe

func IsColorBlindSafe(colors []Color) bool

func LayoutSegments

func LayoutSegments(segs []StyledSegment, maxWidth int) [][]StyledSegment

LayoutSegments lays out StyledSegments into rows of at most maxWidth.

func MeasureSegmentsWidth

func MeasureSegmentsWidth(segs []StyledSegment) int

MeasureSegmentsWidth sums the cell width across a slice of segments.

func MeasureWidth

func MeasureWidth(text string) int

MeasureWidth returns the cell count of a string.

func MeetsWCAG

func MeetsWCAG(fg, bg Color, level string) bool

func PadCenter

func PadCenter(text string, width int) string

PadCenter centers text.

func PadLeft

func PadLeft(text string, width int) string

PadLeft pads with spaces on the left.

func PadRight

func PadRight(text string, width int) string

PadRight pads with spaces on the right.

func ParseBasicMouse

func ParseBasicMouse(data []byte) (bool, int, int, MouseButton, MouseAction)

func ParseSGRMouse

func ParseSGRMouse(data []byte) (bool, int, int, MouseButton, MouseAction)

func RelativeLuminance

func RelativeLuminance(c Color) float64

func RenderText

func RenderText(text string, width int) string

func ResetAttrs

func ResetAttrs(in AttrMask) string

func Run

func Run(model Node) error

Run is the simplest way to start a MOFU application. It creates a Program with sensible defaults and runs it.

func RunWithOpts

func RunWithOpts(model Node, opts ...Option) error

RunWithOpts starts a MOFU application with options.

func RuneWidth

func RuneWidth(r rune) int

RuneWidth returns the terminal display width of a rune via runewidth.

func SendMessage

func SendMessage(dest, message string) error

SendMessage delivers a string message to a destination. Destinations follow routing rules used by the Runtime system: literal channel name for local broadcast, "to:<addr>" for a single recipient, or comma-separated list for fan-out.

func Truncate

func Truncate(text string, maxWidth int, withEllipsis bool) string

Truncate clips text to maxWidth and optionally adds an ellipsis.

func TruncateMiddle

func TruncateMiddle(text string, maxWidth int) string

TruncateMiddle truncates the middle: "Hello World" → "He…ld" at limit 5.

func Width

func Width(w int) string

func WithProgramMessageRouter

func WithProgramMessageRouter(p *Program)

WithProgramMessageRouter connects SendMessage to a Program-level dispatch.

func WordWrap

func WordWrap(text string, maxWidth int) []string

WordWrap wraps text to maxWidth columns, preserving word boundaries.

Types

type Align

type Align int

Align controls cross-axis alignment.

const (
	// AlignLeft aligns content to the left.
	AlignLeft Align = 0
	// AlignCenter centers content.
	AlignCenter Align = 1
	// AlignRight aligns content to the right.
	AlignRight Align = 2
	// AlignStretch stretches content to fill.
	AlignStretch Align = 3
)

type AnimDirection

type AnimDirection int

AnimDirection controls the animation direction.

const (
	AnimForward   AnimDirection = iota // 0 to 1
	AnimReverse                        // 1 to 0
	AnimAlternate                      // forward then reverse
)

type AnimRepeatMode

type AnimRepeatMode int

AnimRepeatMode controls how animations repeat.

const (
	AnimRepeatNone    AnimRepeatMode = iota // play once
	AnimRepeatForever                       // loop forever
	AnimRepeatN                             // loop N times
)

type AnimSequenceGroup

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

AnimSequenceGroup runs animations one after another.

func AnimSequence

func AnimSequence(anims ...*Animation) *AnimSequenceGroup

AnimSequence creates a group that runs animations in order.

func (*AnimSequenceGroup) Done

func (g *AnimSequenceGroup) Done() bool

Done reports whether all animations in the sequence are complete.

func (*AnimSequenceGroup) Update

func (g *AnimSequenceGroup) Update(delta time.Duration)

Update advances the current animation in the sequence.

type AnimTransition

type AnimTransition struct {
	Enter  AnimationSpec
	Exit   AnimationSpec
	Update AnimationSpec
}

AnimTransition defines enter/exit animations for a widget.

func DefaultAnimTransition

func DefaultAnimTransition() AnimTransition

DefaultAnimTransition returns a transition with fade animations.

func SlideAnimTransition

func SlideAnimTransition() AnimTransition

SlideAnimTransition returns a transition with slide animations.

func (AnimTransition) Animation

func (t AnimTransition) Animation(typ AnimTransitionType, from, to float64) *Animation

Animation creates an Animation for the given transition phase.

type AnimTransitionType

type AnimTransitionType int

AnimTransitionType identifies the transition phase.

const (
	AnimTransitionEnter AnimTransitionType = iota
	AnimTransitionExit
	AnimTransitionUpdate
)

type Animation

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

Animation represents a running animation that produces float64 values.

func NewAnimation

func NewAnimation(spec AnimationSpec, from, to float64) *Animation

NewAnimation creates a new animation from a spec.

func Stagger

func Stagger(spec AnimationSpec, staggerDelay time.Duration, fromTos []StaggerFromTo) []*Animation

Stagger creates animations with staggered delays.

func (*Animation) Done

func (a *Animation) Done() bool

Done reports whether the animation has completed.

func (*Animation) OnChange

func (a *Animation) OnChange(fn func(float64))

OnChange registers a callback for each frame's value.

func (*Animation) Reset

func (a *Animation) Reset()

Reset restarts the animation from the beginning.

func (*Animation) Update

func (a *Animation) Update(delta time.Duration) float64

Update advances the animation by delta. Returns the current value.

type AnimationGroup

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

AnimationGroup runs multiple animations simultaneously.

func Parallel

func Parallel(anims ...*Animation) *AnimationGroup

Parallel creates a group that runs all animations simultaneously.

func (*AnimationGroup) Done

func (g *AnimationGroup) Done() bool

Done reports whether all animations in the group are complete.

func (*AnimationGroup) Update

func (g *AnimationGroup) Update(delta time.Duration)

Update advances all animations in the group.

type AnimationSpec

type AnimationSpec struct {
	Duration time.Duration
	Delay    time.Duration
	Easing   EasingFn
	Repeat   AnimRepeatMode
	RepeatN  int
	AnimDir  AnimDirection
}

AnimationSpec is a declarative animation configuration.

func DefaultAnimationSpec

func DefaultAnimationSpec() AnimationSpec

DefaultAnimationSpec returns a spec with sensible defaults.

func QuickSpec

func QuickSpec(duration time.Duration, easing EasingFn) AnimationSpec

QuickSpec creates a spec with just duration and easing.

type Animator

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

Animator manages active tween/spring animations for a Program.

func NewAnimator

func NewAnimator() *Animator

NewAnimator returns an empty Animator.

func (*Animator) AddSpring

func (a *Animator) AddSpring(s *Spring) uint64

AddSpring registers a spring animation and returns its ID.

func (*Animator) AddTween

func (a *Animator) AddTween(from, to float64, durationMs uint64, easing EasingFn, apply func(v float64)) uint64

AddTween registers a tween and returns its ID. Caller supplies Apply(cb) to receive each frame's value.

func (*Animator) CurrentValue

func (a *Animator) CurrentValue(id uint64) (float64, bool)

CurrentValue returns the current interpolated value for a tween by ID. Returns (0, false) if not found or not a tween.

func (*Animator) Remove

func (a *Animator) Remove(id uint64)

Remove cancels an animation by ID.

func (*Animator) Update

func (a *Animator) Update(deltaMs uint64) []uint64

Update advances all animations by deltaMs milliseconds. For completed tweens, Apply is called with the final value before removal. Returns IDs of animations that finished this tick.

type AttrMask

type AttrMask uint16
const (
	AttrBold            AttrMask = 1 << 0
	AttrDim             AttrMask = 1 << 1
	AttrItalic          AttrMask = 1 << 2
	AttrUnderline       AttrMask = 1 << 3
	AttrSlowBlink       AttrMask = 1 << 4
	AttrRapidBlink      AttrMask = 1 << 5
	AttrReverse         AttrMask = 1 << 6
	AttrHidden          AttrMask = 1 << 7
	AttrStrikethrough   AttrMask = 1 << 8
	AttrDoubleUnderline AttrMask = 1 << 9
	AttrOverline        AttrMask = 1 << 10
)

func (AttrMask) Has

func (a AttrMask) Has(flag AttrMask) bool

type Attrs

type Attrs struct {
	Bold, Italic, Underline bool
}

type BaseNode

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

BaseNode provides default implementations for all Node methods. Embed this in your struct to get started with minimal boilerplate.

func (*BaseNode) AddChild

func (n *BaseNode) AddChild(child Node)

func (*BaseNode) Bounds

func (n *BaseNode) Bounds() Rect

func (*BaseNode) Children

func (n *BaseNode) Children() []Node

func (*BaseNode) Dirty

func (n *BaseNode) Dirty() bool

func (*BaseNode) HandleEvent

func (n *BaseNode) HandleEvent(event Event) Cmd

func (*BaseNode) Mount

func (n *BaseNode) Mount() Cmd

func (*BaseNode) RemoveChild

func (n *BaseNode) RemoveChild(child Node)

func (*BaseNode) Render

func (n *BaseNode) Render(ctx *RenderContext)

func (*BaseNode) SetBounds

func (n *BaseNode) SetBounds(r Rect)

func (*BaseNode) SetDirty

func (n *BaseNode) SetDirty()

func (*BaseNode) Style

func (n *BaseNode) Style() *Style

func (*BaseNode) Unmount

func (n *BaseNode) Unmount()

type BatchCoalescer

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

BatchCoalescer coalesces rapid updates into a single update.

func NewBatchCoalescer

func NewBatchCoalescer[T any](signal *Signal[T], interval time.Duration) *BatchCoalescer[T]

NewBatchCoalescer creates a new batch coalescer.

func (*BatchCoalescer[T]) Add

func (b *BatchCoalescer[T]) Add(value T)

Add adds a value to the batch.

type BatchMsg

type BatchMsg []Cmd

BatchMsg runs commands concurrently.

type BorderStyle

type BorderStyle struct {
	Top, Bottom, Left, Right                   rune
	TopLeft, TopRight, BottomLeft, BottomRight rune
}

BorderStyle defines the characters used to draw borders.

type BoxNode

type BoxNode struct {
	BaseNode
}

func NewBox

func NewBox(children ...Node) *BoxNode

func (*BoxNode) HandleEvent

func (n *BoxNode) HandleEvent(event Event) Cmd

func (*BoxNode) Mount

func (n *BoxNode) Mount() Cmd

func (*BoxNode) Render

func (n *BoxNode) Render(ctx *RenderContext)

func (*BoxNode) Unmount

func (n *BoxNode) Unmount()

type Breakpoint

type Breakpoint struct {
	MinWidth int
	Layout   *LayoutNode
}

Breakpoint defines a layout at a specific width.

type CapabilityProfile

type CapabilityProfile struct {
	TrueColor      bool
	ANSI256        bool
	ANSI16         bool
	Mouse          bool
	MouseSGR       bool
	BracketedPaste bool
	Unicode        bool
	AltScreen      bool
	SyncOutput     bool // CSI 2026
	KittyKeyboard  bool
	Width          int
	Height         int
	Terminal       string // e.g. "xterm-256color", "wezterm", "iterm2"
}

CapabilityProfile detects and stores terminal capabilities. Use DetectCapabilities to probe the current terminal.

func DetectCapabilities

func DetectCapabilities() CapabilityProfile

DetectCapabilities probes the terminal environment and returns a capability profile. It checks environment variables and falls back to defaults.

func (CapabilityProfile) ColorDepth

func (p CapabilityProfile) ColorDepth() int

ColorDepth returns the maximum color depth supported.

func (CapabilityProfile) SupportsSGRMouse

func (p CapabilityProfile) SupportsSGRMouse() bool

SupportsSGRMouse reports whether the terminal supports SGR extended mouse.

func (CapabilityProfile) SupportsSyncOutput

func (p CapabilityProfile) SupportsSyncOutput() bool

SupportsSyncOutput reports whether the terminal supports CSI 2026.

type ClearScreenMsg

type ClearScreenMsg struct{}

ClearScreenMsg requests a full screen redraw.

type Cmd

type Cmd func() Msg

Cmd is an IO operation returning a Msg when complete.

var NoCmd Cmd = nil

NoCmd is a no-op.

func Batch

func Batch(cmds ...Cmd) Cmd

Batch runs commands concurrently.

func Every

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

Every produces a message synchronized with the system clock.

func QuitCmd

func QuitCmd() Cmd

QuitCmd returns a Cmd that sends a quit message. Return this from HandleEvent to exit.

func SendCmd

func SendCmd(msg Msg) Cmd

SendCmd returns a Cmd that sends an arbitrary message.

func Sequence

func Sequence(cmds ...Cmd) Cmd

Sequence runs commands in order.

func Tick

func Tick(delay time.Duration, fn func() Msg) Cmd

Tick produces a message after a fixed duration.

type Color

type Color struct {
	R, G, B  uint8
	IsANSI   bool
	ANSICode uint8
}

Color represents a terminal color.

func ANSI

func ANSI(code uint8) Color

ANSI creates an ANSI indexed color.

func BlendColors

func BlendColors(a, b Color, t float64) Color

func Complementary

func Complementary(c Color) Color

func Darken

func Darken(c Color, amount float64) Color

func HSVToRGB

func HSVToRGB(hsv HSV) Color

func Hex

func Hex(hex string) Color

Hex creates a Color from a hex string (e.g. "#ff00ff" or "ff00ff").

func Lighten

func Lighten(c Color, amount float64) Color

func RGB

func RGB(r, g, b uint8) Color

RGB creates a true-color Color.

func TextColorForBackground

func TextColorForBackground(bg Color) Color

type ColorProfile

type ColorProfile struct {
	ANSI4Bit, ANSI256, TrueColor Color
}

type ColorProfileMsg

type ColorProfileMsg struct{ Profile string }

ColorProfileMsg carries the detected terminal color profile.

type ColumnAlign

type ColumnAlign struct {
	Width int
	Align TextAlign
}

ColumnAlign holds width + alignment for a single column.

type Computed

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

Computed is a value derived from signals.

func NewComputed

func NewComputed[T any](compute func() T, signals ...any) *Computed[T]

NewComputed creates a computed value.

func (*Computed[T]) Get

func (c *Computed[T]) Get() T

Get returns the current computed value.

func (*Computed[T]) Subscribe

func (c *Computed[T]) Subscribe(fn func(T)) func()

Subscribe registers a callback for value changes.

type DataCallback

type DataCallback func(oldVal, newVal any)

DataCallback is the legacy callback signature kept for backward compatibility.

type DataNode

type DataNode struct {
	ID      string
	Value   any
	Source  string
	Version int64
	Updated time.Time
	// contains filtered or unexported fields
}

DataNode is a typed state leaf in the graph.

func NewDataNode

func NewDataNode(id string, val any) *DataNode

NewDataNode constructs a state leaf.

func (*DataNode) Get

func (dn *DataNode) Get() any

Get returns the current value under the node.

func (*DataNode) Set

func (dn *DataNode) Set(val any)

Set updates the node value and fans out to exact subscribers.

func (*DataNode) Subscribe

func (dn *DataNode) Subscribe(id string, fn DataCallback)

Subscribe registers a callback keyed by owner id.

func (*DataNode) SubscribePattern

func (dn *DataNode) SubscribePattern(id uint64, pattern SubscribePattern)

SubscribePattern records a wildcard subscription id for later notification.

func (*DataNode) Unsubscribe

func (dn *DataNode) Unsubscribe(id string, fn DataCallback)

Unsubscribe removes an exact listener.

func (*DataNode) UnsubscribePattern

func (dn *DataNode) UnsubscribePattern(id uint64)

UnsubscribePattern removes a pattern listener.

type DataStore

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

DataStore is a centralized state container with subscriptions.

func NewDataStore

func NewDataStore() *DataStore

NewDataStore creates a new store.

func (*DataStore) Get

func (s *DataStore) Get(key string) any

Get returns a value from the store.

func (*DataStore) Restore

func (s *DataStore) Restore(snap map[string]any)

Restore hydrates the store from a snapshot.

func (*DataStore) Set

func (s *DataStore) Set(key string, value any)

Set sets a value in the store and notifies subscribers.

func (*DataStore) Snapshot

func (s *DataStore) Snapshot() map[string]any

Snapshot returns a copy of all state.

func (*DataStore) Subscribe

func (s *DataStore) Subscribe(key string, fn func(any)) func()

Subscribe subscribes to changes for a key.

func (*DataStore) Version

func (s *DataStore) Version() uint64

Version returns the current version.

type DiffResult

type DiffResult struct {
	Type    string // "add", "remove", "update", "move"
	Node    *TreeNode
	Old     *TreeNode
	Changes map[string]any
}

DiffResult describes a change between two tree states.

func DiffTrees

func DiffTrees(old, new *TreeNode) []DiffResult

DiffTrees computes the minimal set of changes between two trees.

type Direction

type Direction int
const (
	DirectionRow    Direction = 0
	DirectionColumn Direction = 1
)

type EasingFn

type EasingFn func(t float64) float64

EasingFn maps normalised progress t∈[0,1] to [0,1].

type Effect

type Effect interface {
	Execute() Msg
	Cancel()
	Done() <-chan struct{}
	ID() string
}

func NewEffect

func NewEffect(name string, fn func() Msg) Effect

func NewRetryEffect

func NewRetryEffect(name string, maxRetries int, fn func() (Msg, error)) Effect

func NewTimerEffect

func NewTimerEffect(name string, delay time.Duration, fn func() Msg) Effect

type EffectRunner

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

EffectRunner runs a side effect when dependencies change.

func NewEffectRunner

func NewEffectRunner(fn func()) *EffectRunner

NewEffectRunner creates a new effect runner.

func (*EffectRunner) OnCleanup

func (e *EffectRunner) OnCleanup(fn func())

OnCleanup registers a cleanup function.

func (*EffectRunner) Run

func (e *EffectRunner) Run()

Run runs the effect and tracks dependencies.

func (*EffectRunner) Stop

func (e *EffectRunner) Stop()

Stop stops the effect and runs cleanups.

type EnvMsg

type EnvMsg map[string]string

EnvMsg carries environment variables.

type Event

type Event struct {
	Type   EventType
	Data   Msg
	Time   time.Time
	Source string
}

Event is a typed event with data and timestamp.

type EventBus

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

func NewEventBus

func NewEventBus() *EventBus

func (*EventBus) Publish

func (eb *EventBus) Publish(event Event)

func (*EventBus) Subscribe

func (eb *EventBus) Subscribe(event string, handler EventHandler)

func (*EventBus) Unsubscribe

func (eb *EventBus) Unsubscribe(event string)

type EventHandler

type EventHandler func(Event)

type EventType

type EventType int

EventType identifies the kind of event.

const (
	// EventKeyPress is a keyboard event.
	EventKeyPress EventType = iota
	// EventMouse is a mouse event.
	EventMouse
	// EventResize is a terminal resize event.
	EventResize
	// EventData is a data event.
	EventData
	// EventAnimation is an animation tick event.
	EventAnimation
	// EventSystem is a system event.
	EventSystem
	// EventCustom is a custom event.
	EventCustom
)

type FrameStats

type FrameStats struct {
	FrameCount int64
	RenderTime time.Duration
	DirtyCells int
	TotalCells int
	FPS        float64
}

FrameStats holds performance metrics for the current frame.

type HSV

type HSV struct {
	H, S, V float64
}

func RGBToHSV

func RGBToHSV(c Color) HSV

type History

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

History manages state snapshots for undo/redo.

func NewHistory

func NewHistory[T any](maxSize int) *History[T]

NewHistory creates a new history manager.

func (*History[T]) CanRedo

func (h *History[T]) CanRedo() bool

CanRedo returns whether redo is possible.

func (*History[T]) CanUndo

func (h *History[T]) CanUndo() bool

CanUndo returns whether undo is possible.

func (*History[T]) Clear

func (h *History[T]) Clear()

Clear clears all history.

func (*History[T]) Push

func (h *History[T]) Push(state T)

Push pushes a state to the undo stack.

func (*History[T]) Redo

func (h *History[T]) Redo() (T, bool)

Redo redoes the last undone action.

func (*History[T]) Undo

func (h *History[T]) Undo() (T, bool)

Undo undoes the last action.

type InterruptMsg

type InterruptMsg struct{}

InterruptMsg signals SIGINT.

type Justify

type Justify int

Justify controls main-axis alignment.

const (
	// JustifyStart aligns to the start.
	JustifyStart Justify = 0
	// JustifyCenter centers content.
	JustifyCenter Justify = 1
	// JustifyEnd aligns to the end.
	JustifyEnd Justify = 2
	// JustifySpaceBetween spaces items evenly.
	JustifySpaceBetween Justify = 3
)

type Key

type Key int

Key is a keyboard key identifier.

const (
	KeyNone Key = iota
	KeyUp
	KeyDown
	KeyRight
	KeyLeft
	KeyEnter
	KeyEsc
	KeyTab
	KeySpace
	KeyBack
	KeyHome
	KeyEnd
	KeyPgUp
	KeyPgDn
	KeyInsert
	KeyDelete
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
	KeyShiftTab

	// Ctrl+key combinations
	KeyCtrlAt           // Ctrl+Space / Ctrl+@
	KeyCtrlA            // Ctrl+A
	KeyCtrlB            // Ctrl+B
	KeyCtrlC            // Ctrl+C
	KeyCtrlD            // Ctrl+D
	KeyCtrlE            // Ctrl+E
	KeyCtrlF            // Ctrl+F
	KeyCtrlG            // Ctrl+G
	KeyCtrlJ            // Ctrl+J
	KeyCtrlK            // Ctrl+K
	KeyCtrlL            // Ctrl+L
	KeyCtrlN            // Ctrl+N
	KeyCtrlO            // Ctrl+O
	KeyCtrlP            // Ctrl+P
	KeyCtrlQ            // Ctrl+Q
	KeyCtrlR            // Ctrl+R
	KeyCtrlS            // Ctrl+S
	KeyCtrlT            // Ctrl+T
	KeyCtrlU            // Ctrl+U
	KeyCtrlV            // Ctrl+V
	KeyCtrlW            // Ctrl+W
	KeyCtrlX            // Ctrl+X
	KeyCtrlY            // Ctrl+Y
	KeyCtrlZ            // Ctrl+Z
	KeyCtrlBackslash    // Ctrl+\
	KeyCtrlCloseBracket // Ctrl+]
	KeyCtrlCaret        // Ctrl+^
	KeyCtrlUnderscore   // Ctrl+_
)

type KeyEvent

type KeyEvent struct {
	Runes            []byte
	Key              Key
	Alt, Ctrl, Shift bool
}

KeyEvent carries keyboard event data.

type KickstartMsg

type KickstartMsg struct{}

KickstartMsg is an internal tick used by the renderer.

type LayoutEngine

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

LayoutEngine computes layouts for a tree of nodes.

func NewLayoutEngine

func NewLayoutEngine(width, height int) *LayoutEngine

NewLayoutEngine creates a new layout engine.

func (*LayoutEngine) Compute

func (le *LayoutEngine) Compute()

Compute computes the layout for the entire tree.

func (*LayoutEngine) GetBounds

func (le *LayoutEngine) GetBounds(node *LayoutNode) Rect

GetBounds returns the computed bounds for a node.

func (*LayoutEngine) Invalidate

func (le *LayoutEngine) Invalidate()

Invalidate marks the layout as dirty.

func (*LayoutEngine) IsDirty

func (le *LayoutEngine) IsDirty() bool

IsDirty returns whether the layout needs recomputation.

func (*LayoutEngine) Resize

func (le *LayoutEngine) Resize(width, height int)

Resize updates the layout engine dimensions.

func (*LayoutEngine) SetRoot

func (le *LayoutEngine) SetRoot(root *LayoutNode)

SetRoot sets the root layout node.

type LayoutNode

type LayoutNode struct {
	Bounds    Rect
	MinWidth  int
	MaxWidth  int
	MinHeight int
	MaxHeight int
	Grow      float64
	Shrink    float64
	Fixed     bool
	Children  []*LayoutNode
}

LayoutNode is a node in the layout tree.

func FixedNode

func FixedNode(width, height int) *LayoutNode

FixedNode creates a fixed-size layout node.

func FlexColumn

func FlexColumn(children []*LayoutNode, gap int) *LayoutNode

FlexColumn creates a vertical flex layout.

func FlexRow

func FlexRow(children []*LayoutNode, gap int) *LayoutNode

FlexRow creates a horizontal flex layout.

func NewGrowNode

func NewGrowNode(grow float64) *LayoutNode

Grow creates a flexible layout node.

type MessageRouter

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

MessageRouter dispatches string messages to destinations.

func NewMessageRouter

func NewMessageRouter(dispatch func(RoutedEvent)) *MessageRouter

NewMessageRouter constructs a router with an optional initial dispatcher.

func (*MessageRouter) SetDispatch

func (r *MessageRouter) SetDispatch(dispatch func(RoutedEvent))

SetDispatch configures the downstream dispatch function.

type Middleware

type Middleware func(SessionHandler) SessionHandler

Middleware wraps a SessionHandler.

func AuthMiddleware

func AuthMiddleware(callback func(sess *SSHSession) bool) Middleware

AuthMiddleware validates SSH connections via public key.

func LoggingMiddleware

func LoggingMiddleware(logger *log.Logger) Middleware

LoggingMiddleware logs SSH session activity. If logger is nil, the default logger is used.

func RateLimitMiddleware

func RateLimitMiddleware(maxConcurrent int) Middleware

RateLimitMiddleware limits concurrent SSH sessions.

type Minimal

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

Minimal provides default implementations for all Node methods except Render and HandleEvent. Embed this in your model to get started fast.

func (*Minimal) AddChild

func (m *Minimal) AddChild(child Node)

func (*Minimal) Bounds

func (m *Minimal) Bounds() Rect

func (*Minimal) Children

func (m *Minimal) Children() []Node

func (*Minimal) Dirty

func (m *Minimal) Dirty() bool

func (*Minimal) Mount

func (m *Minimal) Mount() Cmd

func (*Minimal) RemoveChild

func (m *Minimal) RemoveChild(child Node)

func (*Minimal) SetBounds

func (m *Minimal) SetBounds(r Rect)

func (*Minimal) SetDirty

func (m *Minimal) SetDirty()

func (*Minimal) Style

func (m *Minimal) Style() *Style

func (*Minimal) Unmount

func (m *Minimal) Unmount()

type Model

type Model = Node

Model is the interface that MOFU programs implement. It is compatible with the legacy Node interface via type alias.

type MouseAction

type MouseAction int
const (
	MousePress MouseAction = iota
	MouseRelease
	MouseDrag
	MouseMove
)

type MouseButton

type MouseButton int
const (
	MouseLeft MouseButton = iota
	MouseRight
	MouseMiddle
	MouseWheelUp
	MouseWheelDown
	MouseNone
)

type MouseEvent

type MouseEvent struct {
	X, Y   int
	Button MouseButton
	Action MouseAction
}

type MouseMode

type MouseMode int
const (
	MouseOff MouseMode = iota
	MouseBasic
	MouseSGRMode
)

type MouseState

type MouseState struct {
	X, Y    int
	Pressed bool
	Button  MouseButton
}

type Msg

type Msg any

Msg is any message sent to a Model's HandleEvent.

func ClearScreen

func ClearScreen() Msg

ClearScreen sends a clear message.

func Interrupt

func Interrupt() Msg

Interrupt sends an interrupt message.

func Quit

func Quit() Msg

Quit sends a quit message.

func Raw

func Raw(content any) Msg

Raw writes a raw ANSI sequence.

type Node

type Node interface {
	// Render draws the component within the given bounds.
	Render(ctx *RenderContext)

	// HandleEvent processes keyboard, mouse, and system events. Return a Cmd to dispatch side effects.
	HandleEvent(event Event) Cmd

	// Mount is called when the component is added to the tree. Return a Cmd to run on mount.
	Mount() Cmd

	// Unmount is called when the component is removed from the tree.
	Unmount()

	// Children returns the component's child nodes.
	Children() []Node

	// AddChild adds a child node.
	AddChild(child Node)

	// RemoveChild removes a child node.
	RemoveChild(child Node)

	// SetDirty marks the component as needing re-render.
	SetDirty()

	// Dirty reports whether the component needs re-render.
	Dirty() bool

	// Bounds returns the component's current layout bounds.
	Bounds() Rect

	// SetBounds sets the component's layout bounds.
	SetBounds(Rect)

	// Style returns the component's style for rendering.
	Style() *Style
}

Node is the core interface for all MOFU components. Every widget must implement this interface. Use Minimal as a base to get default implementations for most methods.

type Option

type Option func(*Program)

func WithBackspace

func WithBackspace() Option

func WithFPS

func WithFPS(fps int) Option

func WithHardTabs

func WithHardTabs() Option

func WithInput

func WithInput(r io.Reader) Option

func WithInputEnabled

func WithInputEnabled(enabled bool) Option

func WithOutputWriter

func WithOutputWriter(w io.Writer) Option

func WithSize

func WithSize(w, h int) Option

func WithTheme

func WithTheme(t *Theme) Option

func WithoutCatchPanics

func WithoutCatchPanics() Option

func WithoutRenderer

func WithoutRenderer() Option

func WithoutSignalHandler

func WithoutSignalHandler() Option

type OverlayNode

type OverlayNode struct {
	BaseNode
}

func NewOverlay

func NewOverlay(children ...Node) *OverlayNode

func (*OverlayNode) HandleEvent

func (n *OverlayNode) HandleEvent(event Event) Cmd

func (*OverlayNode) Mount

func (n *OverlayNode) Mount() Cmd

func (*OverlayNode) Render

func (n *OverlayNode) Render(ctx *RenderContext)

func (*OverlayNode) Unmount

func (n *OverlayNode) Unmount()

type Program

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

func New

func New(root Node, opts ...Option) *Program

New creates a new MOFU Program.

func (*Program) DataStore

func (p *Program) DataStore() *DataStore

func (*Program) Dirty

func (p *Program) Dirty() bool

func (*Program) EventBus

func (p *Program) EventBus() *EventBus

func (*Program) Height

func (p *Program) Height() int

func (*Program) Kernel

func (p *Program) Kernel() *kernel.Kernel

func (*Program) Kill

func (p *Program) Kill()

func (*Program) Model

func (p *Program) Model() Model

func (*Program) Renderer

func (p *Program) Renderer() *Renderer

func (*Program) Run

func (p *Program) Run() error

Run initializes the terminal and starts the MOFU event loop.

func (*Program) Send

func (p *Program) Send(msg Msg)

func (*Program) SetDirty

func (p *Program) SetDirty()

func (*Program) Theme

func (p *Program) Theme() *Theme

func (*Program) Wait

func (p *Program) Wait()

func (*Program) Width

func (p *Program) Width() int

type QuitMsg

type QuitMsg struct{}

QuitMsg signals exit.

type RawMsg

type RawMsg struct{ Content any }

RawMsg contains a raw ANSI escape sequence.

type Rect

type Rect struct {
	X, Y, Width, Height int
}

Rect represents a rectangular region in the terminal grid.

func (Rect) Contains

func (r Rect) Contains(x, y int) bool

Contains reports whether the point (x, y) is inside the rectangle.

type RenderContext

type RenderContext struct {
	Renderer *Renderer
	Theme    *Theme
	Frame    int64
	Delta    time.Duration
	Bounds   Rect
}

RenderContext is passed to every Render call and provides the renderer, theme, frame info, and bounds.

type Renderer

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

func NewRenderer

func NewRenderer(w, h int, theme *Theme) *Renderer

func (*Renderer) Clear

func (r *Renderer) Clear()

func (*Renderer) Flush

func (r *Renderer) Flush() string

func (*Renderer) Resize

func (r *Renderer) Resize(w, h int)

func (*Renderer) WriteString

func (r *Renderer) WriteString(text string, x, y int, fg, bg Color, attrs AttrMask)

func (*Renderer) WriteStyledString

func (r *Renderer) WriteStyledString(text string, x, y int, style Style)

type ResponsiveLayout

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

ResponsiveLayout adapts to terminal size.

func NewResponsiveLayout

func NewResponsiveLayout() *ResponsiveLayout

NewResponsiveLayout creates a responsive layout.

func (*ResponsiveLayout) AddBreakpoint

func (rl *ResponsiveLayout) AddBreakpoint(minWidth int, layout *LayoutNode)

AddBreakpoint adds a layout breakpoint.

func (*ResponsiveLayout) GetLayout

func (rl *ResponsiveLayout) GetLayout(width int) *LayoutNode

GetLayout returns the appropriate layout for the given width.

func (*ResponsiveLayout) SetDefault

func (rl *ResponsiveLayout) SetDefault(layout *LayoutNode)

SetDefault sets the default layout.

type ResumeMsg

type ResumeMsg struct{}

ResumeMsg signals resume.

type RichParser

type RichParser struct{}

RichParser parses [bracketed-tag] rich text into StyledSegments.

func (*RichParser) ApplyTag

func (rp *RichParser) ApplyTag(tag string, style *Style)

ApplyTag handles a tag. The `tag` label parameter distinguishes it from applyTag method.

func (*RichParser) Parse

func (rp *RichParser) Parse(input string) []StyledSegment

Parse walks the input and produces styled segments.

type RoutedEvent

type RoutedEvent struct {
	Dest   string
	Msg    Msg
	Source string
}

RoutedEvent carries a message plus routing metadata for tenant dispatch.

type Runtime

type Runtime struct {
	ID      string
	Type    string
	State   string
	Config  RuntimeConfig
	Mounted bool

	UpdateHook func()
	// contains filtered or unexported fields
}

Runtime is the canonical execution state for a Program.

func NewRuntime

func NewRuntime(id, typ string, cfg RuntimeConfig) *Runtime

NewRuntime builds a Runtime from configuration.

func (*Runtime) DirtyRectangles

func (r *Runtime) DirtyRectangles() []Rect

DirtyRectangles returns rendered dirty rectangles. This is a no-op placeholder in this revision; the renderer exposes its own dirty-region source of truth.

func (*Runtime) Mount

func (r *Runtime) Mount()

Mount marks the runtime as mounted.

func (*Runtime) RequestRender

func (r *Runtime) RequestRender()

RequestRender triggers a render. This is a no-op placeholder; runtime callers should use the owning Program's render scheduling.

func (*Runtime) Update

func (r *Runtime) Update(state string)

Update transitions the runtime to a new state.

type RuntimeConfig

type RuntimeConfig struct {
	Source string
	Thread string
	Type   string
}

RuntimeConfig captures the canonical execution configuration for a Program.

type SSHServer

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

SSHServer serves MOFU apps over SSH.

func NewSSHServer

func NewSSHServer(cfg SSHServerConfig) (*SSHServer, error)

NewSSHServer creates a new SSH server.

func (*SSHServer) Close

func (s *SSHServer) Close() error

Close stops the SSH server.

func (*SSHServer) Serve

func (s *SSHServer) Serve(addr string) error

Serve starts listening for SSH connections.

func (*SSHServer) Sessions

func (s *SSHServer) Sessions() int64

Sessions returns the current number of active sessions.

type SSHServerConfig

type SSHServerConfig struct {
	Addr        string
	HostKey     []byte
	NewProgram  func(*SSHSession) *Program
	Middlewares []Middleware
}

SSHServerConfig holds configuration for the SSH server.

type SSHSession

type SSHSession struct {
	ssh.Channel

	IsPty bool
	// contains filtered or unexported fields
}

SSHSession wraps an SSH channel to implement io.ReadWriteCloser.

func (*SSHSession) Close

func (s *SSHSession) Close() error

func (*SSHSession) RemoteAddr

func (s *SSHSession) RemoteAddr() string

type SceneBuffer

type SceneBuffer struct {
	Cells         [][]SceneCell
	Width, Height int
	// contains filtered or unexported fields
}

func NewSceneBuffer

func NewSceneBuffer(w, h int) *SceneBuffer

func (*SceneBuffer) CellWidth

func (sb *SceneBuffer) CellWidth(ch rune) int

func (*SceneBuffer) Clear

func (sb *SceneBuffer) Clear()

func (*SceneBuffer) Set

func (sb *SceneBuffer) Set(x, y int, char rune, fg, bg Color, attrs AttrMask)

type SceneCell

type SceneCell struct {
	Char   rune
	Fg, Bg Color
	Attrs  AttrMask
	Dirty  bool
	Width  int
}

type ScrollNode

type ScrollNode struct {
	BaseNode
	// contains filtered or unexported fields
}

func NewScroll

func NewScroll(child Node) *ScrollNode

func (*ScrollNode) Children

func (n *ScrollNode) Children() []Node

func (*ScrollNode) HandleEvent

func (n *ScrollNode) HandleEvent(event Event) Cmd

func (*ScrollNode) Mount

func (n *ScrollNode) Mount() Cmd

func (*ScrollNode) Render

func (n *ScrollNode) Render(ctx *RenderContext)

func (*ScrollNode) ScrollBy

func (n *ScrollNode) ScrollBy(dx, dy int)

func (*ScrollNode) ScrollTo

func (n *ScrollNode) ScrollTo(x, y int)

func (*ScrollNode) Unmount

func (n *ScrollNode) Unmount()

type SemanticColor

type SemanticColor int

SemanticColor represents a color with semantic meaning.

const (
	SemanticNone SemanticColor = iota
	SemanticSuccess
	SemanticWarning
	SemanticError
	SemanticInfo
	SemanticPrimary
	SemanticSecondary
	SemanticMuted
	SemanticAccent
)

type SemanticColors

type SemanticColors struct {
	TextPrimary   Color
	TextSecondary Color
	TextDisabled  Color
	BorderDefault Color
	BorderFocused Color
	BorderError   Color
	Shadow        Color
}

type SequenceMsg

type SequenceMsg []Cmd

SequenceMsg runs commands in order.

type SessionHandler

type SessionHandler func(sess *SSHSession)

SessionHandler processes a single SSH session.

type Signal

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

Signal is a reactive value that notifies subscribers when changed.

func NewSignal

func NewSignal[T any](initial T) *Signal[T]

NewSignal creates a new reactive signal.

func (*Signal[T]) Get

func (s *Signal[T]) Get() T

Get returns the current value.

func (*Signal[T]) Set

func (s *Signal[T]) Set(value T)

Set updates the value and notifies subscribers.

func (*Signal[T]) Subscribe

func (s *Signal[T]) Subscribe(fn func(T)) func()

Subscribe registers a callback for value changes.

func (*Signal[T]) Version

func (s *Signal[T]) Version() uint64

Version returns the current version (increments on each change).

type Spacing

type Spacing struct{ Top, Right, Bottom, Left int }

Spacing defines padding or margin on all four sides.

func SpacingTokenAll

func SpacingTokenAll(t SpacingToken) Spacing

Spacing returns a Spacing with all sides set to the token value.

type SpacingScale

type SpacingScale struct {
	X0, X1, X2, X4, X8, X12, X16 int
	Scale                        []int
}

type SpacingToken

type SpacingToken int

SpacingToken defines a spacing value by semantic name.

const (
	SpacingNone SpacingToken = iota
	SpacingXXS
	SpacingXS
	SpacingS
	SpacingM
	SpacingL
	SpacingXL
	SpacingXXL
)

func (SpacingToken) Value

func (t SpacingToken) Value() int

SpacingValue returns the cell count for a spacing token.

type Spring

type Spring struct {
	Current   float64
	Target    float64
	Velocity  float64
	Stiffness float64
	Damping   float64
	Mass      float64
}

Spring provides damped-spring interpolation for a single float64 value.

func AnimatePosition

func AnimatePosition(current, target float64) *Spring

AnimatePosition creates a position animation with spring physics.

func NewSpring

func NewSpring(current float64) *Spring

NewSpring creates a spring anchored at current.

func (*Spring) Advance

func (s *Spring) Advance(deltaMs uint64)

Advance advances the spring simulation by deltaMs (milliseconds).

func (*Spring) IsAtRest

func (s *Spring) IsAtRest() bool

IsAtRest reports whether the spring has settled near its target.

func (*Spring) SetTarget

func (s *Spring) SetTarget(t float64)

SetTarget changes the spring's resting value.

type SpringEntry

type SpringEntry struct {
	Spring *Spring
}

SpringEntry holds state for a single spring.

type StackNode

type StackNode struct {
	BaseNode
}

func NewColumn

func NewColumn(children ...Node) *StackNode

func NewRow

func NewRow(children ...Node) *StackNode

func (*StackNode) HandleEvent

func (n *StackNode) HandleEvent(event Event) Cmd

func (*StackNode) Mount

func (n *StackNode) Mount() Cmd

func (*StackNode) Render

func (n *StackNode) Render(ctx *RenderContext)

func (*StackNode) Unmount

func (n *StackNode) Unmount()

type StaggerFromTo

type StaggerFromTo struct {
	From, To float64
}

StaggerFromTo is a from/to value pair for stagger animations.

type State

type State int

State is the lifecycle state of the Program.

const (
	StateInit State = iota
	StateReady
	StateRunning
	StatePaused
	StateStopping
	StateDone
	StateError
)

func ProgramState

func ProgramState(p *Program) State

ProgramState returns the current Program lifecycle state from the active Program instance.

func (State) String

func (s State) String() string

type StateChangeListener

type StateChangeListener func(path string, oldVal, newVal any)

StateChangeListener is called with the path that changed and the new value.

type StateGraph

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

StateGraph holds the application state as a path-addressed reactive tree. It is the core differentiator from other TUI frameworks: widgets only redraw when their subscribed paths change.

func NewStateGraph

func NewStateGraph() *StateGraph

NewStateGraph builds an empty reactive state graph.

func (*StateGraph) DirtyPaths

func (sg *StateGraph) DirtyPaths(sinceVersion uint64) []string

DirtyPaths returns paths that changed since sinceVersion, or nil when unchanged.

func (*StateGraph) Get

func (sg *StateGraph) Get(path string) (any, bool)

Get reads the value at path.

func (*StateGraph) GetNode

func (sg *StateGraph) GetNode(path string) *DataNode

GetNode exposes the underlying leaf for advanced callers.

func (*StateGraph) Restore

func (sg *StateGraph) Restore(snap map[string]any)

Restore hydrates the graph from a snapshot, broadcasting changed paths.

func (*StateGraph) Set

func (sg *StateGraph) Set(path string, val any) bool

Set writes a value at path, creating the node when missing. Bubbles the change to exact and pattern subscribers.

func (*StateGraph) Snapshot

func (sg *StateGraph) Snapshot() map[string]any

Snapshot returns a copy of the entire graph.

func (*StateGraph) SubscribePath

func (sg *StateGraph) SubscribePath(pattern SubscribePattern, fn StateChangeListener) uint64

SubscribePath registers fn for changes matching pattern and returns a handle that can be passed to Unsubscribe.

func (*StateGraph) Unsubscribe

func (sg *StateGraph) Unsubscribe(id uint64)

Unsubscribe removes a path listener and its pattern bindings.

func (*StateGraph) Version

func (sg *StateGraph) Version() uint64

Version returns the monotonically increasing graph version.

type StateMachine

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

StateMachine tracks lifecycle state transitions and notifies listeners on changes.

func (*StateMachine) History

func (sm *StateMachine) History() []Transition

History returns a copy of recorded transitions.

func (*StateMachine) OnChange

func (sm *StateMachine) OnChange(fn func(from, to State))

OnChange registers a lifecycle hook.

func (*StateMachine) State

func (sm *StateMachine) State() State

State returns the current state.

func (*StateMachine) TransitionTo

func (sm *StateMachine) TransitionTo(to State) bool

TransitionTo attempts to change state. It returns whether the transition was accepted.

type Stream

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

Stream is a continuous data source with backpressure.

func NewStream

func NewStream[T any](name string, buffer int) *Stream[T]

NewStream creates a new stream.

func (*Stream[T]) Backlog

func (s *Stream[T]) Backlog() int32

Backlog returns the number of pending items.

func (*Stream[T]) Close

func (s *Stream[T]) Close()

Close closes the stream.

func (*Stream[T]) Done

func (s *Stream[T]) Done() <-chan struct{}

Done returns a channel that's closed when the stream is done.

func (*Stream[T]) Name

func (s *Stream[T]) Name() string

Name returns the stream name.

func (*Stream[T]) Receive

func (s *Stream[T]) Receive() (T, bool)

Receive receives data from the stream.

func (*Stream[T]) Send

func (s *Stream[T]) Send(value T) bool

Send sends data to the stream (non-blocking).

type Style

type Style struct {
	Foreground Color
	Background Color
	Attrs      AttrMask
	Border     BorderStyle
	Margin     Spacing
	Padding    Spacing
	Width      int
	Height     int
	MinWidth   int
	MinHeight  int
	MaxWidth   int
	MaxHeight  int
	Align      Align
	Gap        int
	Grow       float64
	Shrink     float64
	Direction  Direction
	Opacity    float64
	OffsetX    int
	OffsetY    int
	Gutter     int
	// contains filtered or unexported fields
}

func DefaultStyle

func DefaultStyle() Style

func SemanticBg

func SemanticBg(sc SemanticColor, theme *Theme) Style

SemanticBg returns a Style with the background set to the semantic color.

func SemanticFg

func SemanticFg(sc SemanticColor, theme *Theme) Style

SemanticFg returns a Style with the foreground set to the semantic color from the given theme. Falls back to a default if theme is nil.

func (Style) Apply

func (s Style) Apply(text string) string

func (Style) Bg

func (s Style) Bg(c Color) Style

func (Style) Fg

func (s Style) Fg(c Color) Style

func (Style) MarginAll

func (s Style) MarginAll(v int) Style

func (Style) PaddingAll

func (s Style) PaddingAll(v int) Style

func (Style) Reset

func (s Style) Reset() string

func (Style) SGR

func (s Style) SGR() string

func (Style) WithAttrs

func (s Style) WithAttrs(flags AttrMask) Style

func (Style) WithBorder

func (s Style) WithBorder(bs BorderStyle) Style

type StyledChar

type StyledChar struct {
	Ch    rune
	Width int
	Style Style
}

StyledChar is a single character with display width and style.

type StyledSegment

type StyledSegment struct {
	Text  string
	Style Style
}

StyledSegment is a run of text sharing one mofu.Style.

func ParseRichText

func ParseRichText(input string) []StyledSegment

ParseRichText parses tagged text.

type SubscribePattern

type SubscribePattern struct {
	Exact    string
	Prefix   string
	Suffix   string
	Contains string
}

SubscribePattern describes how a path subscription matches DataNode IDs.

func (SubscribePattern) Matches

func (p SubscribePattern) Matches(id string) bool

Matches reports whether id satisfies the pattern.

func (SubscribePattern) String

func (p SubscribePattern) String() string

type SuspendMsg

type SuspendMsg struct{}

SuspendMsg signals suspend (ctrl+z).

type TextAlign

type TextAlign uint8

TextAlign specifies how text is aligned inside a line.

const (
	TextAlignLeft    TextAlign = 0
	TextAlignCenter  TextAlign = 1
	TextAlignRight   TextAlign = 2
	TextAlignJustify TextAlign = 3
)

type TextLayout

type TextLayout struct {
	Lines      []string
	Width      int
	Height     int
	LineWidths []int
}

TextLayout holds pre-computed layout for a block of styled text.

func LayoutText

func LayoutText(text string, cfg TextRendererConfig, align TextAlign) TextLayout

LayoutText computes a TextLayout with wrapping + alignment.

type TextNode

type TextNode struct {
	BaseNode
	Content string
}

func NewText

func NewText(content string) *TextNode

func (*TextNode) Render

func (n *TextNode) Render(ctx *RenderContext)

type TextRendererConfig

type TextRendererConfig struct {
	WrapWidth int
	Ellipsis  bool
	TabWidth  int
	WordWrap  bool
}

TextRendererConfig controls wrapping, ellipsis, and tab-width.

func DefaultTextRendererConfig

func DefaultTextRendererConfig() TextRendererConfig

DefaultTextRendererConfig returns sensible defaults.

type Theme

type Theme struct {
	Name       string         `json:"name"`
	Version    string         `json:"version,omitempty"`
	Colors     ThemeColors    `json:"colors"`
	Semantic   SemanticColors `json:"semantic"`
	Typography Typography     `json:"typography"`
	Spacing    SpacingScale   `json:"spacing"`
	Border     BorderStyle    `json:"-"`
	Radius     int            `json:"radius"`
	Widgets    WidgetThemes   `json:"widgets"`
}

func CatppuccinMocha

func CatppuccinMocha() *Theme

func DefaultTheme

func DefaultTheme() *Theme

func MochiTheme

func MochiTheme() *Theme

type ThemeColors

type ThemeColors struct {
	Background Color   `json:"background"`
	Surface    Color   `json:"surface"`
	Text       Color   `json:"text"`
	TextDim    Color   `json:"textDim"`
	Primary    Color   `json:"primary"`
	Secondary  Color   `json:"secondary"`
	Muted      Color   `json:"muted"`
	Accent     Color   `json:"accent"`
	Success    Color   `json:"success"`
	Warning    Color   `json:"warning"`
	Error      Color   `json:"error"`
	Info       Color   `json:"info"`
	Border     Color   `json:"border"`
	Neutral    []Color `json:"neutral,omitempty"`
}

type ThemeManager

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

ThemeManager manages theme registration, switching, and change notifications.

func NewThemeManager

func NewThemeManager(initial *Theme) *ThemeManager

NewThemeManager creates a theme manager with an initial theme.

func (*ThemeManager) Apply

func (tm *ThemeManager) Apply(name string) bool

Apply switches to the named theme. Returns false if not found.

func (*ThemeManager) Current

func (tm *ThemeManager) Current() *Theme

Current returns the currently active theme.

func (*ThemeManager) LoadFile

func (tm *ThemeManager) LoadFile(path string) error

func (*ThemeManager) Names

func (tm *ThemeManager) Names() []string

func (*ThemeManager) OnChange

func (tm *ThemeManager) OnChange(fn func(old, new *Theme))

func (*ThemeManager) Register

func (tm *ThemeManager) Register(name string, theme *Theme)

Register adds a theme with the given name.

type Transition

type Transition struct {
	From State
	To   State
}

Transition records a state change.

func (Transition) String

func (t Transition) String() string

func (Transition) Valid

func (t Transition) Valid() bool

Valid returns true if the transition is allowed.

type TreeNode

type TreeNode struct {
	ID       string
	Type     string
	Props    map[string]any
	Children []*TreeNode
	Parent   *TreeNode
	Style    *Style
	Bounds   Rect
	Visible  bool
	Focused  bool
	Dirty    bool
	// contains filtered or unexported fields
}

TreeNode is a node in the rendering tree.

func NewTreeNode

func NewTreeNode(id, nodeType string) *TreeNode

NewTreeNode creates a new tree node.

func (*TreeNode) AddChild

func (n *TreeNode) AddChild(child *TreeNode)

AddChild adds a child node.

func (*TreeNode) Emit

func (n *TreeNode) Emit(event Event)

Emit emits an event to listeners.

func (*TreeNode) Find

func (n *TreeNode) Find(id string) *TreeNode

Find finds a node by ID in the subtree.

func (*TreeNode) FindByType

func (n *TreeNode) FindByType(nodeType string) []*TreeNode

FindByType finds all nodes of a given type.

func (*TreeNode) GetProp

func (n *TreeNode) GetProp(key string) any

GetProp gets a property from the node.

func (*TreeNode) On

func (n *TreeNode) On(event string, handler func(Event))

On adds an event listener.

func (*TreeNode) RemoveChild

func (n *TreeNode) RemoveChild(id string)

RemoveChild removes a child node.

func (*TreeNode) SetProp

func (n *TreeNode) SetProp(key string, value any)

SetProp sets a property on the node.

type TreeRenderer

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

TreeRenderer renders a tree of nodes to the terminal.

func NewTreeRenderer

func NewTreeRenderer(root *TreeNode, renderer *Renderer, theme *Theme) *TreeRenderer

NewTreeRenderer creates a new tree renderer.

func (*TreeRenderer) FindNode

func (tr *TreeRenderer) FindNode(id string) *TreeNode

FindNode finds a node by ID.

func (*TreeRenderer) Render

func (tr *TreeRenderer) Render(bounds Rect)

Render renders the entire tree.

func (*TreeRenderer) Root

func (tr *TreeRenderer) Root() *TreeNode

Root returns the root node.

func (*TreeRenderer) UpdateTree

func (tr *TreeRenderer) UpdateTree(newRoot *TreeNode)

UpdateTree updates the tree and renders changes.

type TweenEntry

type TweenEntry struct {
	From, To   float64
	DurationMs uint64
	ElapsedMs  uint64
	Easing     EasingFn
	Apply      func(v float64) // callback to apply value each frame
}

TweenEntry holds state for a single tween.

type Typography

type Typography struct {
	Title, Subtitle, Body, Label, Mono Style
}

type Vec2

type Vec2 struct {
	X, Y float64
}

Vec2 is a 2D point used by layout, scroll, and animation systems.

func Vec2XY

func Vec2XY(x, y float64) Vec2

Vec2XY creates a Vec2 from x, y coordinates.

type WidgetTheme

type WidgetTheme struct {
	Normal, Focused, Hover, Pressed, Disabled, Error Style
}

type WidgetThemes

type WidgetThemes struct {
	Button    WidgetTheme
	Input     WidgetTheme
	List      WidgetTheme
	Scrollbar WidgetTheme
	Checkbox  WidgetTheme
	Radio     WidgetTheme
	Progress  WidgetTheme
}

type WindowSizeMsg

type WindowSizeMsg struct{ Width, Height int }

WindowSizeMsg carries terminal dimensions.

Directories

Path Synopsis
Package agent provides AI-native TUI components for agentic workflows.
Package agent provides AI-native TUI components for agentic workflows.
Package ascii provides a procedural ASCII scene engine for MOFU.
Package ascii provides a procedural ASCII scene engine for MOFU.
cmd
mofu command
examples
aiworkflow command
budget command
calculator command
chat command
counter command
csvviewer command
dashboard command
dockerui command
email command
filemanager command
form command
gitui command
kanban command
logmonitor command
logviewer command
markdown command
monitor command
musicplayer command
notepad command
pomodoro command
settings command
stocktracker command
taskmanager command
wizard command
Package kernel provides the execution core for MOFU (Modular Orchestrated Flow Utility).
Package kernel provides the execution core for MOFU (Modular Orchestrated Flow Utility).
Package render provides the zero-allocation differential rendering engine for MOFU (Modular Orchestrated Flow Utility).
Package render provides the zero-allocation differential rendering engine for MOFU (Modular Orchestrated Flow Utility).

Jump to

Keyboard shortcuts

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