runtime

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

runtime/html.go

Package runtime provides a widget runtime for terminal UIs. It implements a constraint-based layout system with focus management and a modal stack for overlays.

Index

Constants

This section is empty.

Variables

View Source
var ZeroRect = Rect{}

ZeroRect is the zero value rect.

Functions

func ApplyState

func ApplyState(root Widget, snapshot PersistSnapshot) error

ApplyState walks the widget tree and restores Persistable state by widget key.

func AutoBind

func AutoBind(services Services, signals ...state.Subscribable) func()

AutoBind observes multiple signals and invalidates the widget when any change. Nil signals in the variadic list are silently skipped. Returns a cleanup function that unsubscribes all observers; call it in Unbind.

Usage:

func (w *MyWidget) Bind(s runtime.Services) {
    w.services = s
    w.cleanup = runtime.AutoBind(s, w.label, w.count, w.enabled)
}

func (w *MyWidget) Unbind() {
    w.cleanup()
    w.services = runtime.Services{}
}

func AutoBindRelayout

func AutoBindRelayout(services Services, signals ...state.Subscribable) func()

AutoBindRelayout is like AutoBind but triggers a full relayout instead of just a render invalidation. Use this for signals that affect widget size (e.g., visibility toggles, text content that changes dimensions).

func BindTree

func BindTree(root Widget, services Services)

BindTree calls Bind on widgets that implement Bindable.

func DefaultUpdate

func DefaultUpdate(app *App, msg Message) bool

DefaultUpdate handles input messages and widget commands.

func LayoutDebugEnabled

func LayoutDebugEnabled() bool

LayoutDebugEnabled reports whether layout diagnostics are enabled. It is enabled by default when FLUFFYUI_LAYOUT_DEBUG is a truthy value.

func MountTree

func MountTree(root Widget)

MountTree calls Mount on widgets that implement Lifecycle.

func RegisterFocusables

func RegisterFocusables(scope *FocusScope, root Widget)

RegisterFocusables registers focusable widgets from the tree into the scope.

func RegisterMCPEnabler

func RegisterMCPEnabler(fn mcpEnableFunc)

RegisterMCPEnabler registers the MCP implementation hook.

func RenderChild

func RenderChild(ctx RenderContext, child Widget) bool

RenderChild renders a child widget if it intersects the current context bounds. Returns true if the widget was rendered.

func SaveSnapshot

func SaveSnapshot(path string, snapshot PersistSnapshot) error

SaveSnapshot writes a snapshot to disk as JSON.

func SetLayoutDebug

func SetLayoutDebug(enabled bool)

SetLayoutDebug enables or disables layout diagnostics at runtime.

func SetLayoutDebugWriter

func SetLayoutDebugWriter(w io.Writer)

SetLayoutDebugWriter overrides the destination for layout diagnostics. Passing nil restores os.Stderr.

func UnbindTree

func UnbindTree(root Widget)

UnbindTree calls Unbind on widgets that implement Unbindable.

func UnmountTree

func UnmountTree(root Widget)

UnmountTree calls Unmount on widgets that implement Lifecycle.

func WarnInvalidConstraints

func WarnInvalidConstraints(scope string, c Constraints)

WarnInvalidConstraints emits a debug warning when constraints are impossible to satisfy (min > max in either dimension).

func WarnZeroMeasure

func WarnZeroMeasure(scope string, c Constraints, measured Size)

WarnZeroMeasure emits a debug warning for zero-size measurements when constraints would allow visible output.

func WatchStylesheetFile

func WatchStylesheetFile(app *App, path string, interval time.Duration) func()

WatchStylesheetFile watches a stylesheet file and applies updates on the app loop. It returns a stop function to halt polling.

Types

type App

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

App runs a widget tree against a terminal backend.

func NewApp

func NewApp(cfg AppConfig) *App

NewApp creates a new App from config.

func (*App) After

func (a *App) After(delay time.Duration, msg Message)

After schedules a delayed message using the app task context.

func (*App) Animator

func (a *App) Animator() *animation.Animator

Animator returns the app animator.

func (*App) Call

func (a *App) Call(ctx context.Context, fn func(*App) error) error

Call runs fn on the app's event loop and waits for it to finish. Call blocks until the function completes or the context is done. Call must not be invoked from the app's update/render goroutine.

func (*App) DragActive

func (a *App) DragActive() bool

DragActive reports whether a drag operation is in progress.

func (*App) DragData

func (a *App) DragData() *DragData

DragData returns the data for the active drag, or nil if no drag is active.

func (*App) EnableMCP

func (a *App) EnableMCP(opts ...MCPOptions) (io.Closer, error)

EnableMCP starts the MCP server for the app.

func (*App) Every

func (a *App) Every(interval time.Duration, fn func(time.Time) Message)

Every schedules a recurring message using the app task context.

func (*App) ExecuteCommand

func (a *App) ExecuteCommand(cmd Command) bool

ExecuteCommand runs a command through the app handler.

func (*App) Invalidate

func (a *App) Invalidate()

Invalidate requests a render pass.

func (*App) InvalidateScheduler

func (a *App) InvalidateScheduler() state.Scheduler

InvalidateScheduler returns a scheduler that invalidates the render pass.

func (*App) Localizer

func (a *App) Localizer() i18n.Localizer

Localizer returns the active localizer.

func (*App) Post

func (a *App) Post(msg Message)

Post sends a message to the event loop.

func (*App) PostQueueFlush

func (a *App) PostQueueFlush()

PostQueueFlush requests a state queue flush.

func (*App) Relayout

func (a *App) Relayout()

Relayout recomputes layout and invalidates the render pass.

func (*App) Run

func (a *App) Run(ctx context.Context) error

Run starts the event loop until quit or context cancellation.

func (*App) Screen

func (a *App) Screen() *Screen

Screen returns the active screen, if initialized.

func (*App) Services

func (a *App) Services() Services

Services returns a service handle for the app.

func (*App) SetLocalizer

func (a *App) SetLocalizer(localizer i18n.Localizer)

SetLocalizer updates the app localizer.

func (*App) SetRoot

func (a *App) SetRoot(root Widget)

SetRoot swaps the root widget.

func (*App) SetStylesheet

func (a *App) SetStylesheet(sheet *style.Stylesheet)

SetStylesheet replaces the active stylesheet and invalidates the render pass.

func (*App) SetTheme

func (a *App) SetTheme(th *theme.Theme)

SetTheme replaces the active theme and rebuilds the stylesheet.

func (*App) SnapshotText

func (a *App) SnapshotText() string

SnapshotText returns a snapshot of the current screen buffer as plain text. The snapshot is taken under the render lock to avoid tearing.

func (*App) Spawn

func (a *App) Spawn(effect Effect)

Spawn starts an effect using the app task context. If Run has not started, the effect is queued until start.

func (*App) StateQueue

func (a *App) StateQueue() *state.Queue

StateQueue returns the app's state queue.

func (*App) StateScheduler

func (a *App) StateScheduler() state.Scheduler

StateScheduler returns a scheduler that wakes the app to flush.

func (*App) Stylesheet

func (a *App) Stylesheet() *style.Stylesheet

Stylesheet returns the active stylesheet.

func (*App) Theme

func (a *App) Theme() *theme.Theme

Theme returns the active theme, if set.

func (*App) TryPost

func (a *App) TryPost(msg Message) bool

TryPost sends a message to the event loop without blocking.

type AppConfig

type AppConfig struct {
	Backend           backend.Backend
	InlineMode        bool
	InlineHeight      int
	Root              Widget
	Update            UpdateFunc
	CommandHandler    CommandHandler
	MessageBuffer     int
	TickRate          time.Duration
	StateQueue        *state.Queue
	FlushPolicy       QueueFlushPolicy
	KeyHandler        KeyHandler
	Announcer         accessibility.Announcer
	Clipboard         clipboard.Clipboard
	FocusStyle        *accessibility.FocusStyle
	Recorder          Recorder
	RenderObserver    RenderObserver
	FocusRegistration FocusRegistrationMode
	AutoFocusPolicy   AutoFocusPolicy
	Audio             audio.Service
	Theme             *theme.Theme
	Stylesheet        *style.Stylesheet
	Animator          *animation.Animator
	ReducedMotion     bool
	FrameBudget       time.Duration
	Localizer         i18n.Localizer
	ErrorReporter     *ErrorReporter
	Speaker           accessibility.Speaker
	MCPOptions        *MCPOptions
	OnReady           func(app *App)
	OnResize          func(app *App, width, height int)
	OnQuit            func(app *App)
}

AppConfig configures a runtime App.

type AutoFocusPolicy

type AutoFocusPolicy int

AutoFocusPolicy controls how FocusScope handles initial focus.

const (
	// AutoFocusFirst focuses the first registered focusable widget (default).
	AutoFocusFirst AutoFocusPolicy = iota
	// AutoFocusLast focuses the last registered focusable widget.
	AutoFocusLast
	// AutoFocusNone disables auto-focus; apps must call SetFocus explicitly.
	AutoFocusNone
)

type Bindable

type Bindable interface {
	Bind(services Services)
}

Bindable widgets receive app services when mounted into a screen.

type BoundsProvider

type BoundsProvider interface {
	Bounds() Rect
}

BoundsProvider reports the widget's assigned bounds.

type Buffer

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

Buffer is a 2D grid of cells for rendering widgets. Widgets render to the buffer, then the buffer is flushed to the backend. Supports dirty-region tracking for partial redraws.

func NewBuffer

func NewBuffer(w, h int) *Buffer

NewBuffer creates a buffer with the given dimensions.

func (*Buffer) Cells

func (b *Buffer) Cells() []Cell

Cells returns the underlying cell slice.

func (*Buffer) Clear

func (b *Buffer) Clear()

Clear fills the buffer with spaces and default style.

func (*Buffer) ClearDirty

func (b *Buffer) ClearDirty()

ClearDirty resets all dirty flags.

func (*Buffer) ClearImageOps

func (b *Buffer) ClearImageOps()

ClearImageOps clears queued image operations.

func (*Buffer) ClearRect

func (b *Buffer) ClearRect(r Rect)

ClearRect fills a rectangular region with spaces and default style.

func (*Buffer) DirtyCount

func (b *Buffer) DirtyCount() int

DirtyCount returns the number of dirty cells.

func (*Buffer) DirtyRect

func (b *Buffer) DirtyRect() Rect

DirtyRect returns the bounding box of dirty cells. Returns empty rect if nothing is dirty.

func (*Buffer) DrawBox

func (b *Buffer) DrawBox(r Rect, s backend.Style)

DrawBox draws a border around a rect using box-drawing characters.

func (*Buffer) DrawDoubleBox

func (b *Buffer) DrawDoubleBox(r Rect, s backend.Style)

DrawDoubleBox draws a border with double-line characters.

func (*Buffer) DrawRoundedBox

func (b *Buffer) DrawRoundedBox(r Rect, s backend.Style)

DrawRoundedBox draws a border with rounded corners.

func (*Buffer) Fill

func (b *Buffer) Fill(r Rect, ch rune, s backend.Style)

Fill fills a rectangular region with a rune and style. Marks changed cells as dirty.

func (*Buffer) ForEachDirtyCell

func (b *Buffer) ForEachDirtyCell(fn func(x, y int, cell Cell))

ForEachDirtyCell calls fn for each dirty cell. More efficient than iterating all cells when few are dirty.

func (*Buffer) ForEachDirtySpan

func (b *Buffer) ForEachDirtySpan(fn func(y, startX, endX int))

ForEachDirtySpan calls fn for each contiguous dirty span per row.

func (*Buffer) Get

func (b *Buffer) Get(x, y int) Cell

Get returns the cell at position (x, y). Returns empty cell if out of bounds.

func (*Buffer) ImageOps

func (b *Buffer) ImageOps() []imageOp

ImageOps returns queued image operations.

func (*Buffer) IsCellDirty

func (b *Buffer) IsCellDirty(x, y int) bool

IsCellDirty returns true if the cell at (x, y) is dirty.

func (*Buffer) IsDirty

func (b *Buffer) IsDirty() bool

IsDirty returns true if any cells have changed.

func (*Buffer) MarkAllDirty

func (b *Buffer) MarkAllDirty()

MarkAllDirty marks the entire buffer as dirty.

func (*Buffer) Resize

func (b *Buffer) Resize(w, h int)

Resize changes the buffer dimensions, preserving content where possible.

func (*Buffer) Set

func (b *Buffer) Set(x, y int, r rune, s backend.Style)

Set writes a rune with style at position (x, y). No-op if out of bounds. Marks the cell as dirty if changed.

func (*Buffer) SetContent

func (b *Buffer) SetContent(x, y int, mainc rune, _ []rune, style backend.Style)

SetContent implements backend.RenderTarget.

func (*Buffer) SetImage

func (b *Buffer) SetImage(x, y int, img backend.Image)

SetImage queues an image render and clears its cell region.

func (*Buffer) SetString

func (b *Buffer) SetString(x, y int, s string, style backend.Style)

SetString writes a string starting at (x, y). Clips to buffer bounds. Marks changed cells as dirty.

func (*Buffer) Size

func (b *Buffer) Size() (w, h int)

Size returns the buffer dimensions.

func (*Buffer) SnapshotText

func (b *Buffer) SnapshotText() string

SnapshotText returns the buffer content as plain text. Callers are responsible for external synchronization if needed.

func (*Buffer) Sub

func (b *Buffer) Sub(r Rect) *SubBuffer

Sub creates a SubBuffer for the given region.

type Cancel

type Cancel struct{}

Cancel indicates an operation was cancelled (e.g., Escape pressed).

func (Cancel) Command

func (Cancel) Command()

type Cell

type Cell = backend.Cell

Cell represents a single character cell in the buffer.

type ChildProvider

type ChildProvider interface {
	ChildWidgets() []Widget
}

ChildProvider exposes child widgets for container traversal.

type Command

type Command interface {
	Command()
}

Command represents an action/intent emitted by widgets. Commands bubble up from widgets to the app for handling.

func Send

func Send(msg Message) Command

Send wraps a message in a SendMsg command.

type CommandHandler

type CommandHandler func(cmd Command) bool

CommandHandler handles commands emitted by widgets. Return true if the command requires a render.

type Constraints

type Constraints struct {
	MinWidth, MaxWidth   int
	MinHeight, MaxHeight int
}

Constraints define the min/max space available to a widget during measure.

func Loose

func Loose(w, h int) Constraints

Loose returns constraints with only max bounds (min = 0).

func Tight

func Tight(w, h int) Constraints

Tight returns constraints that force an exact size.

func TightHeight

func TightHeight(h int) Constraints

TightHeight returns constraints with flexible width, exact height.

func TightWidth

func TightWidth(w int) Constraints

TightWidth returns constraints with exact width, flexible height.

func Unbounded

func Unbounded() Constraints

Unbounded returns constraints with no limits.

func (Constraints) Constrain

func (c Constraints) Constrain(s Size) Size

Constrain clamps a size to fit within these constraints.

func (Constraints) IsTight

func (c Constraints) IsTight() bool

IsTight returns true if min equals max for both dimensions.

func (Constraints) MaxSize

func (c Constraints) MaxSize() Size

MaxSize returns the maximum size allowed by constraints.

func (Constraints) MinSize

func (c Constraints) MinSize() Size

MinSize returns the minimum size required by constraints.

type CustomMsg

type CustomMsg struct {
	Value any
}

CustomMsg allows applications to define their own message types. The Value field can hold any application-specific data.

Example usage:

type MyStreamChunk struct {
    SessionID string
    Text      string
}

app.Post(runtime.CustomMsg{Value: MyStreamChunk{...}})

// In update function:
case runtime.CustomMsg:
    switch v := m.Value.(type) {
    case MyStreamChunk:
        // handle stream chunk
    }

type DragData

type DragData struct {
	Source Widget      // the widget being dragged from
	Kind   string      // type identifier (e.g., "list-item", "tree-node")
	Value  interface{} // the dragged data
	Label  string      // display label for the drag indicator
}

DragData represents data being dragged.

type DragEndMsg

type DragEndMsg struct {
	Data      DragData
	Target    Widget // nil if cancelled
	Cancelled bool
}

DragEndMsg is a command sent when a drag completes or is cancelled.

func (DragEndMsg) Command

func (DragEndMsg) Command()

Command implements the Command interface.

type DragSource

type DragSource interface {
	// IsDraggable returns true if dragging is enabled on this widget.
	IsDraggable() bool
}

DragSource is implemented by widgets that can initiate drags.

type DragStartMsg

type DragStartMsg struct{ Data DragData }

DragStartMsg is a command sent when a drag begins.

func (DragStartMsg) Command

func (DragStartMsg) Command()

Command implements the Command interface.

type DropTarget

type DropTarget interface {
	// CanDrop returns true if this widget accepts the given drag data.
	CanDrop(data DragData) bool
	// OnDrop handles the drop, returning true if accepted.
	OnDrop(data DragData) bool
}

DropTarget is implemented by widgets that accept drops.

type Effect

type Effect struct {
	Run func(ctx context.Context, post PostFunc)
}

Effect runs work in a background goroutine. Use the provided context for cancellation and PostFunc to emit messages.

func After

func After(delay time.Duration, msg Message) Effect

After posts a message after a delay.

func Every

func Every(interval time.Duration, fn func(time.Time) Message) Effect

Every posts messages on a fixed interval. Returning nil from fn skips posting.

func (Effect) Command

func (Effect) Command()

type ErrorBoundary

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

ErrorBoundary wraps a widget and catches panics during Render and HandleMessage. When a panic is caught, the boundary renders a red error message instead of the child widget. Use Reset to clear the error and retry.

func NewErrorBoundary

func NewErrorBoundary(child Widget) *ErrorBoundary

NewErrorBoundary creates an ErrorBoundary wrapping the given child widget.

func (*ErrorBoundary) Blur

func (eb *ErrorBoundary) Blur()

Blur delegates to the child if it implements Focusable.

func (*ErrorBoundary) Bounds

func (eb *ErrorBoundary) Bounds() Rect

Bounds returns the assigned bounds.

func (*ErrorBoundary) CanFocus

func (eb *ErrorBoundary) CanFocus() bool

CanFocus delegates to the child if it implements Focusable.

func (*ErrorBoundary) ChildWidgets

func (eb *ErrorBoundary) ChildWidgets() []Widget

ChildWidgets returns the child widget for container traversal.

func (*ErrorBoundary) Error

func (eb *ErrorBoundary) Error() error

Error returns the captured error, or nil if none.

func (*ErrorBoundary) Focus

func (eb *ErrorBoundary) Focus()

Focus delegates to the child if it implements Focusable.

func (*ErrorBoundary) HandleMessage

func (eb *ErrorBoundary) HandleMessage(msg Message) HandleResult

HandleMessage dispatches a message to the child widget, catching any panics. If the boundary is in an error state, messages are silently consumed.

func (*ErrorBoundary) IsFocused

func (eb *ErrorBoundary) IsFocused() bool

IsFocused delegates to the child if it implements Focusable.

func (*ErrorBoundary) Layout

func (eb *ErrorBoundary) Layout(bounds Rect)

Layout stores the bounds and delegates to the child widget, catching any panics. If in an error state, only stores the bounds without delegating.

func (*ErrorBoundary) Measure

func (eb *ErrorBoundary) Measure(constraints Constraints) Size

Measure delegates to the child widget, catching any panics. Returns zero if the child is nil, or the minimum constraint size if in an error state.

func (*ErrorBoundary) Render

func (eb *ErrorBoundary) Render(ctx RenderContext)

Render draws the child widget, catching any panics. If the boundary is in an error state, it renders a red error message instead.

func (*ErrorBoundary) Reset

func (eb *ErrorBoundary) Reset()

Reset clears the error state so the child widget will be rendered again.

type ErrorReporter

type ErrorReporter struct {
	ShowStackTrace bool
	ShowWidgetTree bool
	Writer         io.Writer
	RootProvider   func() Widget
}

ErrorReporter formats widget errors with context.

func (*ErrorReporter) ReportWidgetError

func (er *ErrorReporter) ReportWidgetError(widget Widget, err error, msg Message)

ReportWidgetError outputs a formatted error report for a widget.

type FileSelected

type FileSelected struct {
	Path string
}

FileSelected indicates a file was chosen in the file picker.

func (FileSelected) Command

func (FileSelected) Command()

type Flex

type Flex struct {
	Direction    FlexDirection
	Children     []FlexChild
	Gap          int           // Space between children
	MeasureCache *MeasureCache // Optional measurement cache (set by Screen)
	// contains filtered or unexported fields
}

Flex is a container that lays out children along an axis.

func HBox

func HBox(children ...FlexChild) *Flex

HBox creates a horizontal flex container.

func VBox

func VBox(children ...FlexChild) *Flex

VBox creates a vertical flex container.

func (*Flex) Add

func (f *Flex) Add(child FlexChild)

Add appends a child to the flex container.

func (*Flex) Bounds

func (f *Flex) Bounds() Rect

Bounds returns the assigned bounds for the flex container.

func (*Flex) ChildWidgets

func (f *Flex) ChildWidgets() []Widget

ChildWidgets returns the flex container's child widgets.

func (*Flex) HandleMessage

func (f *Flex) HandleMessage(msg Message) HandleResult

HandleMessage dispatches to children. Messages go to all children; first handler wins.

func (*Flex) Layout

func (f *Flex) Layout(bounds Rect)

Layout positions all children within the given bounds.

func (*Flex) Measure

func (f *Flex) Measure(constraints Constraints) Size

Measure calculates the desired size of the flex container.

func (*Flex) PathSegment

func (f *Flex) PathSegment(child Widget) string

PathSegment returns a debug path segment for the given child.

func (*Flex) Render

func (f *Flex) Render(ctx RenderContext)

Render draws all children.

func (*Flex) RenderHTML

func (f *Flex) RenderHTML(ctx HTMLContext) HTML

RenderHTML renders the flex layout as static HTML.

func (*Flex) WithGap

func (f *Flex) WithGap(gap int) *Flex

WithGap sets the gap between children.

type FlexChild

type FlexChild struct {
	Widget Widget
	Grow   float64 // How much to grow (0 = fixed, 1+ = proportional)
	Shrink float64 // How much to shrink (0 = fixed, 1+ = proportional)
	Basis  int     // Base size (-1 = use measured size)
}

FlexChild wraps a widget with flex layout properties.

func Expanded

func Expanded(w Widget) FlexChild

Expanded creates a child that grows to fill available space (Grow=1).

func Fixed

func Fixed(w Widget) FlexChild

Fixed creates a child that doesn't grow or shrink.

func FixedSpace

func FixedSpace(size int) FlexChild

FixedSpace creates a fixed-size spacer.

func Flexible

func Flexible(w Widget, grow float64) FlexChild

Flexible creates a child that grows with the given factor.

func Sized

func Sized(w Widget, basis int) FlexChild

Sized creates a child with a fixed basis size.

func Space

func Space() FlexChild

Space creates a flexible spacer that expands to fill available space.

type FlexDirection

type FlexDirection int

FlexDirection specifies the main axis of a flex container.

const (
	Column FlexDirection = iota // Vertical (VBox)
	Row                         // Horizontal (HBox)
)

type FocusChangedMsg

type FocusChangedMsg struct {
	Prev Focusable
	Next Focusable
}

FocusChangedMsg reports a focus transition.

type FocusLayoutAffecting

type FocusLayoutAffecting interface {
	FocusAffectsLayout() bool
}

FocusLayoutAffecting reports whether focus changes can affect layout. Implement this on widgets whose focus state impacts measurement or layout.

type FocusNext

type FocusNext struct{}

FocusNext requests focus move to the next focusable widget.

func (FocusNext) Command

func (FocusNext) Command()

type FocusPrev

type FocusPrev struct{}

FocusPrev requests focus move to the previous focusable widget.

func (FocusPrev) Command

func (FocusPrev) Command()

type FocusRegistrationMode

type FocusRegistrationMode int

FocusRegistrationMode configures how focusables are registered.

const (
	// FocusRegistrationManual requires apps to register focusables explicitly.
	FocusRegistrationManual FocusRegistrationMode = iota
	// FocusRegistrationAuto scans widget trees on root/layer changes.
	FocusRegistrationAuto
)

type FocusRestore

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

FocusRestore saves focused widgets on a stack for later restoration. This is used by modal dialogs, popovers, and dropdowns to return focus to the element that triggered them when they close.

func (*FocusRestore) Len

func (fr *FocusRestore) Len() int

Len returns the number of saved entries.

func (*FocusRestore) Pop

func (fr *FocusRestore) Pop() Focusable

Pop removes and returns the most recently saved widget. Returns nil if the stack is empty.

func (*FocusRestore) Push

func (fr *FocusRestore) Push(current Focusable)

Push saves a focusable widget onto the stack.

type FocusScope

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

FocusScope manages focus within a layer/context. Each modal layer has its own FocusScope, so overlays trap focus.

func NewFocusScope

func NewFocusScope() *FocusScope

NewFocusScope creates a new empty focus scope with default auto-focus policy.

func NewFocusScopeWithPolicy

func NewFocusScopeWithPolicy(policy AutoFocusPolicy) *FocusScope

NewFocusScopeWithPolicy creates a focus scope with the specified auto-focus policy.

func (*FocusScope) ClearFocus

func (f *FocusScope) ClearFocus()

ClearFocus removes focus from the current widget.

func (*FocusScope) Count

func (f *FocusScope) Count() int

Count returns the number of registered widgets.

func (*FocusScope) Current

func (f *FocusScope) Current() Focusable

Current returns the currently focused widget, or nil.

func (*FocusScope) FocusFirst

func (f *FocusScope) FocusFirst() bool

FocusFirst focuses the first focusable widget.

func (*FocusScope) FocusLast

func (f *FocusScope) FocusLast() bool

FocusLast focuses the last focusable widget.

func (*FocusScope) FocusNext

func (f *FocusScope) FocusNext() bool

FocusNext moves focus to the next focusable widget. Wraps around to the first widget if at the end. Returns true if focus changed.

func (*FocusScope) FocusPrev

func (f *FocusScope) FocusPrev() bool

FocusPrev moves focus to the previous focusable widget. Wraps around to the last widget if at the beginning. Returns true if focus changed.

func (*FocusScope) Register

func (f *FocusScope) Register(w Focusable)

Register adds a focusable widget to the scope. Auto-focus behavior depends on the scope's AutoFocusPolicy.

func (*FocusScope) Reset

func (f *FocusScope) Reset()

Reset clears focus and forgets all registered widgets.

func (*FocusScope) SetAutoFocusPolicy

func (f *FocusScope) SetAutoFocusPolicy(policy AutoFocusPolicy)

SetAutoFocusPolicy changes the auto-focus policy.

func (*FocusScope) SetFocus

func (f *FocusScope) SetFocus(w Focusable) bool

SetFocus focuses a specific widget. Returns true if focus changed.

func (*FocusScope) SetOnChange

func (f *FocusScope) SetOnChange(fn func(prev Focusable, next Focusable))

SetOnChange registers a focus change callback.

func (*FocusScope) Unregister

func (f *FocusScope) Unregister(w Focusable)

Unregister removes a widget from the scope. If it was focused, focus moves to the next available widget.

type Focusable

type Focusable interface {
	Widget

	// CanFocus returns true if this widget can currently receive focus.
	CanFocus() bool

	// Focus is called when the widget gains focus.
	Focus()

	// Blur is called when the widget loses focus.
	Blur()

	// IsFocused returns true if this widget currently has focus.
	IsFocused() bool
}

Focusable extends Widget for widgets that can receive keyboard focus.

type HTML

type HTML = template.HTML

HTML is an alias for template.HTML so widget packages need not import html/template.

type HTMLContext

type HTMLContext struct {
	Depth int // nesting depth for optional indentation
}

HTMLContext carries state for HTML rendering.

func (HTMLContext) Child

func (ctx HTMLContext) Child() HTMLContext

Child returns a context for rendering child widgets.

type HTMLRenderer

type HTMLRenderer interface {
	RenderHTML(ctx HTMLContext) HTML
}

HTMLRenderer is implemented by widgets that can render to static HTML.

type HandleResult

type HandleResult struct {
	Handled  bool      // Was the message consumed?
	Commands []Command // Commands to send to parent/app
	// contains filtered or unexported fields
}

HandleResult is returned from HandleMessage.

func Handled

func Handled() HandleResult

Handled returns a result indicating the message was consumed.

func Unhandled

func Unhandled() HandleResult

Unhandled returns a result indicating the message was not consumed.

func WithCommand

func WithCommand(cmd Command) HandleResult

WithCommand returns a handled result with a single command.

func WithCommands

func WithCommands(cmds ...Command) HandleResult

WithCommands returns a handled result with multiple commands.

type HitGrid

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

HitGrid maps screen cells to widgets for mouse hit testing.

func NewHitGrid

func NewHitGrid(width, height int) *HitGrid

NewHitGrid creates a new hit grid with the given dimensions.

func (*HitGrid) Add

func (g *HitGrid) Add(widget Widget, bounds Rect)

Add records a widget occupying the specified bounds.

func (*HitGrid) Clear

func (g *HitGrid) Clear()

Clear resets the grid contents.

func (*HitGrid) Resize

func (g *HitGrid) Resize(width, height int)

Resize updates the hit grid dimensions.

func (*HitGrid) WidgetAt

func (g *HitGrid) WidgetAt(x, y int) Widget

WidgetAt returns the widget at the given screen position.

type HitSelfProvider

type HitSelfProvider interface {
	HitSelf() bool
}

HitSelfProvider allows containers to receive mouse hits for their own bounds. When true, the container is added to the hit grid after its children.

type Invalidatable

type Invalidatable interface {
	Invalidate()
	NeedsRender() bool
	ClearInvalidation()
}

Invalidatable marks widgets that can report whether they need a render pass.

type InvalidateMsg

type InvalidateMsg struct{}

InvalidateMsg requests a render pass without forcing a full redraw.

type Invalidator

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

Invalidator posts an invalidate message with coalescing.

func NewInvalidator

func NewInvalidator(post func(Message) bool) *Invalidator

NewInvalidator creates an invalidator wired to a post function.

func (*Invalidator) Invalidate

func (i *Invalidator) Invalidate()

Invalidate requests a render pass.

func (*Invalidator) Schedule

func (i *Invalidator) Schedule(fn func())

Schedule runs fn and requests a render pass.

type KeyHandler

type KeyHandler interface {
	HandleKey(app *App, msg KeyMsg, focused Widget) bool
}

KeyHandler handles key events before widget dispatch.

type KeyMsg

type KeyMsg struct {
	Key   terminal.Key
	Rune  rune
	Alt   bool
	Ctrl  bool
	Shift bool
}

KeyMsg represents a keyboard input event.

type Keyed

type Keyed interface {
	Key() string
}

Keyed identifies widgets with stable identity for diffing/persistence.

type Layer

type Layer struct {
	Root       Widget
	FocusScope *FocusScope
	Modal      bool // If true, blocks input to layers below
}

Layer represents a layer in the modal stack. Each layer has its own widget tree and focus scope.

type Lifecycle

type Lifecycle interface {
	Mount()
	Unmount()
}

Lifecycle is implemented by widgets that need mount/unmount hooks.

type MCPOptions

type MCPOptions struct {
	// Transport
	Transport string // "stdio", "unix", or "sse" (auto-detected if empty)
	Addr      string // Socket path or HTTP address

	// Security
	AllowText      bool   // Include raw screen text in snapshots
	AllowClipboard bool   // Enable clipboard tools
	Token          string // Auth token (optional)

	// Sessions
	SessionTimeout time.Duration // Inactivity timeout (default: 30m)
	MaxSessions    int           // Max concurrent (default: 10)

	// Rate limiting
	RateLimit        int    // Requests per second (0 = unlimited)
	BurstLimit       int    // Burst allowance (default: RateLimit * 2)
	MaxPendingEvents int    // Subscription backlog (default: 100)
	SlowClientPolicy string // "drop_oldest" | "drop_newest" | "disconnect"

	// Behavior
	StrictLabelMatching bool // Error on ambiguous labels

	// Testing only (panics in release builds)
	TestBypassTextGating      bool
	TestBypassClipboardGating bool
}

MCPOptions configures the MCP server integration.

type MeasureCache

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

MeasureCache stores cached measurement results for widgets, keyed by widget identity and constraints. Entries are accepted from the current generation or the immediately preceding one, allowing measurements to persist across a single relayout pass without growing stale.

func NewMeasureCache

func NewMeasureCache() *MeasureCache

NewMeasureCache creates a new empty measure cache starting at generation 1.

func (*MeasureCache) BumpGeneration

func (c *MeasureCache) BumpGeneration() int64

BumpGeneration increments the generation counter, evicts stale entries, and returns the new value.

func (*MeasureCache) Clear

func (c *MeasureCache) Clear()

Clear removes all cached entries.

func (*MeasureCache) Generation

func (c *MeasureCache) Generation() int64

Generation returns the current generation counter.

func (*MeasureCache) Get

func (c *MeasureCache) Get(w Widget, constraints Constraints, gen int64) (Size, bool)

Get returns the cached measurement if constraints match and the entry's generation is current (gen) or immediately prior (gen-1).

func (*MeasureCache) Invalidate

func (c *MeasureCache) Invalidate(w Widget)

Invalidate removes a specific widget's cached measurement.

func (*MeasureCache) Len

func (c *MeasureCache) Len() int

Len returns the number of cached entries (used for testing/diagnostics).

func (*MeasureCache) Set

func (c *MeasureCache) Set(w Widget, constraints Constraints, result Size, gen int64)

Set stores a measurement result for a widget with the given constraints and generation.

type Message

type Message interface {
	// contains filtered or unexported methods
}

Message represents an event flowing into the UI. Messages come from terminal input, timers, or background goroutines.

type MessagePriority

type MessagePriority int

MessagePriority indicates how urgently a message should be processed.

const (
	// PriorityHigh is for keyboard, focus, and accessibility messages
	// that must be processed with minimal latency.
	PriorityHigh MessagePriority = iota

	// PriorityNormal is for mouse, paste, resize, and custom messages.
	PriorityNormal

	// PriorityLow is for tick, invalidate, and queue flush messages
	// that can tolerate some delay.
	PriorityLow
)

type MountHook

type MountHook interface {
	OnMountHook()
}

MountHook is implemented by widgets that support an onMount lifecycle callback. BindTree calls OnMountHook after Bind so hooks fire even when a widget defines its own Bind that does not chain to Base.

type MouseAction

type MouseAction int

MouseAction identifies what happened with the mouse.

const (
	MousePress MouseAction = iota
	MouseRelease
	MouseMove
)

type MouseButton

type MouseButton int

MouseButton identifies which mouse button was involved.

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

type MouseMsg

type MouseMsg struct {
	X, Y   int
	Button MouseButton
	Action MouseAction
	Alt    bool
	Ctrl   bool
	Shift  bool
}

MouseMsg represents a mouse input event.

type PaletteSelected

type PaletteSelected struct {
	ID   string // Item identifier
	Data any    // Custom data from the item
}

PaletteSelected indicates an item was chosen from a palette.

func (PaletteSelected) Command

func (PaletteSelected) Command()

type PasteMsg

type PasteMsg struct {
	Text string
}

PasteMsg represents pasted text from bracketed paste mode.

type PathSegmenter

type PathSegmenter interface {
	PathSegment(child Widget) string
}

PathSegmenter customizes widget path segments for error reporting. Implementations can include child-specific context (e.g., Grid[row,col]).

type PersistSnapshot

type PersistSnapshot struct {
	Widgets map[string]json.RawMessage `json:"widgets"`
}

PersistSnapshot stores serialized widget state keyed by widget key.

func CaptureState

func CaptureState(root Widget) (PersistSnapshot, error)

CaptureState walks the widget tree and captures Persistable state keyed by widget Key().

func LoadSnapshot

func LoadSnapshot(path string) (PersistSnapshot, error)

LoadSnapshot reads a snapshot from disk.

type Persistable

type Persistable interface {
	MarshalState() ([]byte, error)
	UnmarshalState([]byte) error
}

Persistable captures widget state for persistence.

type PopOverlay

type PopOverlay struct{}

PopOverlay requests the top overlay be dismissed.

func (PopOverlay) Command

func (PopOverlay) Command()

type PostFunc

type PostFunc func(Message) bool

PostFunc sends a message into the app. It returns false when the message queue is full.

type PriorityQueue

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

PriorityQueue routes messages into priority-stratified channels so that high-priority events (keyboard input) are never blocked behind bulk low-priority traffic (timer ticks, invalidations).

func NewPriorityQueue

func NewPriorityQueue(size int) *PriorityQueue

NewPriorityQueue creates a PriorityQueue with buffered channels of the given size per priority level.

func (*PriorityQueue) Recv

func (q *PriorityQueue) Recv(ctx context.Context) (Message, bool)

Recv returns the highest-priority pending message, blocking only when all channels are empty. It returns (nil, false) when ctx is cancelled.

Drain order: high before normal, normal before low.

func (*PriorityQueue) Send

func (q *PriorityQueue) Send(msg Message)

Send classifies msg and sends it to the appropriate priority channel. If the target channel is full, Send drops the message (non-blocking).

func (*PriorityQueue) TrySend

func (q *PriorityQueue) TrySend(msg Message) bool

TrySend classifies msg and attempts a non-blocking send. It returns true if the message was enqueued, false if the channel was full.

type PushOverlay

type PushOverlay struct {
	Widget Widget
	Modal  bool
}

PushOverlay requests a modal overlay be pushed.

func (PushOverlay) Command

func (PushOverlay) Command()

type QueueFlushMsg

type QueueFlushMsg struct{}

QueueFlushMsg triggers a state queue flush in the update loop.

type QueueFlushPolicy

type QueueFlushPolicy int

QueueFlushPolicy configures when the app flushes state queues.

const (
	// FlushOnMessageAndTick flushes on any message or tick.
	FlushOnMessageAndTick QueueFlushPolicy = iota
	// FlushOnMessage flushes on messages except TickMsg.
	FlushOnMessage
	// FlushOnTick flushes only on TickMsg.
	FlushOnTick
	// FlushManual flushes only on QueueFlushMsg.
	FlushManual
)

type QueueScheduler

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

QueueScheduler enqueues callbacks and wakes the app to flush.

func NewQueueScheduler

func NewQueueScheduler(queue *state.Queue, post func(Message) bool) *QueueScheduler

NewQueueScheduler wires a queue to a post function.

func (*QueueScheduler) Schedule

func (s *QueueScheduler) Schedule(fn func())

Schedule enqueues the callback and posts a flush message.

type Quit

type Quit struct{}

Quit signals the application should exit.

func (Quit) Command

func (Quit) Command()

type Recorder

type Recorder interface {
	Start(width, height int, now time.Time) error
	Resize(width, height int) error
	Frame(buffer *Buffer, now time.Time) error
	Close() error
}

Recorder captures rendered frames for playback/export.

type Rect

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

Rect is a positioned rectangle.

func NewRect

func NewRect(x, y, w, h int) Rect

NewRect creates a rect from position and size.

func RectFromSize

func RectFromSize(s Size) Rect

RectFromSize creates a rect at origin with the given size.

func (Rect) Contains

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

Contains returns true if the point is inside the rect.

func (Rect) Inset

func (r Rect) Inset(top, right, bottom, left int) Rect

Inset returns a rect shrunk by the given amounts.

func (Rect) Intersection

func (r Rect) Intersection(other Rect) Rect

Intersection returns the overlapping area of two rects.

func (Rect) Intersects

func (r Rect) Intersects(other Rect) bool

Intersects returns true if the two rects overlap.

func (Rect) Size

func (r Rect) Size() Size

Size returns the rect's dimensions as a Size.

type Refresh

type Refresh struct{}

Refresh requests a screen redraw.

func (Refresh) Command

func (Refresh) Command()

type RenderContext

type RenderContext struct {
	Buffer  *Buffer
	Focused bool // Is the containing layer focused?
	Bounds  Rect // Widget's allocated bounds
	// contains filtered or unexported fields
}

RenderContext provides context to widgets during rendering.

func (RenderContext) Clear

func (ctx RenderContext) Clear(style backend.Style)

Clear fills the context bounds with spaces using the provided style.

func (RenderContext) ResolveBackendStyle

func (ctx RenderContext) ResolveBackendStyle(widget Widget) backend.Style

ResolveBackendStyle returns a backend style for the widget.

func (RenderContext) ResolveStyle

func (ctx RenderContext) ResolveStyle(widget Widget) style.Style

ResolveStyle returns the resolved stylesheet style for the widget.

func (RenderContext) Sub

func (ctx RenderContext) Sub(bounds Rect) RenderContext

Sub creates a new context for a child widget with adjusted bounds.

func (RenderContext) SubBuffer

func (ctx RenderContext) SubBuffer() *SubBuffer

SubBuffer returns a buffer view clipped to the context bounds.

func (RenderContext) SubVisible

func (ctx RenderContext) SubVisible(bounds Rect) (RenderContext, bool)

SubVisible returns a child context and whether it is visible.

func (RenderContext) Visible

func (ctx RenderContext) Visible(bounds Rect) bool

Visible reports whether the given bounds intersect the current context bounds.

func (RenderContext) WithBuffer

func (ctx RenderContext) WithBuffer(buffer *Buffer, bounds Rect) RenderContext

WithBuffer returns a new context that renders into the provided buffer.

type RenderObserver

type RenderObserver interface {
	ObserveRender(stats RenderStats)
}

RenderObserver receives render timing and dirty stats.

type RenderObserverFunc

type RenderObserverFunc func(stats RenderStats)

RenderObserverFunc adapts a function into a RenderObserver.

func (RenderObserverFunc) ObserveRender

func (f RenderObserverFunc) ObserveRender(stats RenderStats)

ObserveRender invokes the wrapped function.

type RenderSampler

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

RenderSampler collects recent render stats for quick profiling summaries.

func NewRenderSampler

func NewRenderSampler(window int) *RenderSampler

NewRenderSampler creates a sampler retaining the last N samples.

func (*RenderSampler) ObserveRender

func (r *RenderSampler) ObserveRender(stats RenderStats)

ObserveRender records a render sample.

func (*RenderSampler) Summary

func (r *RenderSampler) Summary() RenderSummary

Summary returns aggregate stats for the current sample window.

type RenderStats

type RenderStats struct {
	Frame          int64
	Started        time.Time
	Ended          time.Time
	TotalDuration  time.Duration
	RenderDuration time.Duration
	FlushDuration  time.Duration
	DirtyCells     int
	FlushedCells   int
	TotalCells     int
	FullRedraw     bool
	DirtyRect      Rect
	LayerCount     int
}

RenderStats captures timing and dirty-region data for a render pass.

type RenderSummary

type RenderSummary struct {
	Frames        int64
	Samples       int
	Window        int
	Last          RenderStats
	AvgTotal      time.Duration
	AvgRender     time.Duration
	AvgFlush      time.Duration
	AvgDirtyRatio float64
	MaxTotal      time.Duration
	MaxRender     time.Duration
	MaxFlush      time.Duration
}

RenderSummary aggregates a window of render samples.

type ResizeMsg

type ResizeMsg struct {
	Width  int
	Height int
}

ResizeMsg indicates the terminal size changed.

type Screen

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

Screen manages the widget tree, modal stack, and rendering.

func NewScreen

func NewScreen(w, h int) *Screen

NewScreen creates a new screen with the given dimensions.

func (*Screen) BaseFocusScope

func (s *Screen) BaseFocusScope() *FocusScope

BaseFocusScope returns the focus scope of the base layer. Use this when you need the focus scope that contains the main widgets, as overlay layers (like toast stacks) may be on top.

func (*Screen) BaseLayer

func (s *Screen) BaseLayer() *Layer

BaseLayer returns the base (bottom) layer.

func (*Screen) Buffer

func (s *Screen) Buffer() *Buffer

Buffer returns the screen's render buffer.

func (*Screen) FocusScope

func (s *Screen) FocusScope() *FocusScope

FocusScope returns the focus scope of the top layer.

func (*Screen) HandleMessage

func (s *Screen) HandleMessage(msg Message) HandleResult

HandleMessage dispatches a message to the appropriate layer. Messages go to the top layer. If not handled and not modal, they bubble down to lower layers.

func (*Screen) Layer

func (s *Screen) Layer(i int) *Layer

Layer returns the layer at index i (0 = base layer). Returns nil if index is out of bounds.

func (*Screen) LayerCount

func (s *Screen) LayerCount() int

LayerCount returns the number of layers.

func (*Screen) MeasureCache

func (s *Screen) MeasureCache() *MeasureCache

MeasureCache returns the screen's measurement cache. Containers (like Flex) use this to avoid redundant Measure calls.

func (*Screen) OverlayCount

func (s *Screen) OverlayCount() int

OverlayCount returns the number of overlay layers (total layers minus the base layer).

func (*Screen) PopLayer

func (s *Screen) PopLayer() bool

PopLayer removes the top layer from the stack. Returns false if only the base layer remains (can't pop it).

func (*Screen) PushLayer

func (s *Screen) PushLayer(root Widget, modal bool)

PushLayer adds a new layer on top of the stack. If modal is true, input won't pass to layers below.

func (*Screen) RefreshFocusables

func (s *Screen) RefreshFocusables()

RefreshFocusables rescans all layers for focusable widgets.

func (*Screen) Render

func (s *Screen) Render()

Render draws all layers to the buffer.

func (*Screen) Resize

func (s *Screen) Resize(w, h int)

Resize changes the screen dimensions.

func (*Screen) Root

func (s *Screen) Root() Widget

Root returns the base layer's root widget.

func (*Screen) SetAutoFocusPolicy

func (s *Screen) SetAutoFocusPolicy(policy AutoFocusPolicy)

SetAutoFocusPolicy sets the auto-focus policy for newly created focus scopes.

func (*Screen) SetAutoRegisterFocus

func (s *Screen) SetAutoRegisterFocus(enabled bool)

SetAutoRegisterFocus enables or disables automatic focus registration.

func (*Screen) SetErrorReporter

func (s *Screen) SetErrorReporter(reporter *ErrorReporter)

SetErrorReporter configures error reporting for widget panics.

func (*Screen) SetRoot

func (s *Screen) SetRoot(root Widget)

SetRoot sets the root widget of the base layer. Creates the base layer if it doesn't exist.

func (*Screen) SetServices

func (s *Screen) SetServices(services Services)

SetServices configures app services for bindable widgets.

func (*Screen) Size

func (s *Screen) Size() (w, h int)

Size returns the screen dimensions.

func (*Screen) TopLayer

func (s *Screen) TopLayer() *Layer

TopLayer returns the topmost layer.

func (*Screen) WidgetAt

func (s *Screen) WidgetAt(x, y int) Widget

WidgetAt returns the widget at the given screen position.

type SendMsg

type SendMsg struct {
	Message Message
}

SendMsg posts a message into the app loop.

func (SendMsg) Command

func (SendMsg) Command()

type Services

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

Services exposes app-level scheduling and messaging helpers.

func (Services) After

func (s Services) After(delay time.Duration, msg Message)

After schedules a delayed message.

func (Services) Animator

func (s Services) Animator() *animation.Animator

Animator returns the app animator.

func (Services) Announcer

func (s Services) Announcer() accessibility.Announcer

Announcer returns the accessibility announcer.

func (Services) Audio

func (s Services) Audio() audio.Service

Audio returns the app audio service.

func (Services) Clipboard

func (s Services) Clipboard() clipboard.Clipboard

Clipboard returns the app clipboard.

func (Services) Every

func (s Services) Every(interval time.Duration, fn func(time.Time) Message)

Every schedules a recurring message.

func (Services) FocusStyle

func (s Services) FocusStyle() *accessibility.FocusStyle

FocusStyle returns the global focus style.

func (Services) Invalidate

func (s Services) Invalidate()

Invalidate requests a render pass.

func (Services) InvalidateScheduler

func (s Services) InvalidateScheduler() state.Scheduler

InvalidateScheduler returns the app invalidation scheduler.

func (Services) Localizer

func (s Services) Localizer() i18n.Localizer

Localizer returns the active localizer.

func (Services) Post

func (s Services) Post(msg Message) bool

Post sends a message into the app loop.

func (Services) ReducedMotion

func (s Services) ReducedMotion() bool

ReducedMotion reports whether motion should be minimized.

func (Services) Relayout

func (s Services) Relayout()

Relayout requests a layout pass followed by a render.

func (Services) RestoreFocus

func (s Services) RestoreFocus()

RestoreFocus pops the most recently saved widget from the focus restoration stack and refocuses it. Call this when a modal dialog, popover, or dropdown closes to return focus to the element that triggered it.

func (Services) SaveFocus

func (s Services) SaveFocus()

SaveFocus pushes the currently focused widget onto the focus restoration stack. Call this before opening a modal dialog, popover, or dropdown so that focus can be returned to the triggering element when the overlay closes.

func (Services) Scheduler

func (s Services) Scheduler() state.Scheduler

Scheduler returns the app state scheduler.

func (Services) Spawn

func (s Services) Spawn(effect Effect)

Spawn starts an effect using the app task context.

func (Services) Stylesheet

func (s Services) Stylesheet() *style.Stylesheet

Stylesheet returns the active stylesheet.

func (Services) Theme

func (s Services) Theme() *theme.Theme

Theme returns the active theme, if set.

type Size

type Size struct {
	Width, Height int
}

Size is a widget's measured dimensions.

func (Size) Zero

func (s Size) Zero() bool

Zero returns true if both dimensions are zero.

type Spacer

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

Spacer is a flexible empty widget for adding space in flex layouts.

func NewSpacer

func NewSpacer() *Spacer

NewSpacer creates a spacer widget.

func (*Spacer) Bounds

func (s *Spacer) Bounds() Rect

Bounds returns the assigned bounds for the spacer.

func (*Spacer) HandleMessage

func (s *Spacer) HandleMessage(msg Message) HandleResult

func (*Spacer) Layout

func (s *Spacer) Layout(bounds Rect)

func (*Spacer) Measure

func (s *Spacer) Measure(constraints Constraints) Size

func (*Spacer) Render

func (s *Spacer) Render(ctx RenderContext)

type StyleApplier

type StyleApplier interface {
	ApplyStyle(style.Style)
}

StyleApplier receives resolved stylesheet styles for layout.

type StyleClassProvider

type StyleClassProvider interface {
	StyleClasses() []string
}

StyleClassProvider supplies selector classes.

type StyleIDProvider

type StyleIDProvider interface {
	StyleID() string
}

StyleIDProvider supplies a selector ID.

type StyleResolver

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

StyleResolver resolves stylesheet rules against widgets.

func (*StyleResolver) ResetCache

func (r *StyleResolver) ResetCache()

ResetCache clears cached resolved styles while keeping parent maps.

func (*StyleResolver) Resolve

func (r *StyleResolver) Resolve(widget Widget, focused bool) style.Style

Resolve returns the resolved style for a widget.

type StyleStateProvider

type StyleStateProvider interface {
	StyleState() style.WidgetState
}

StyleStateProvider supplies widget pseudo-class state.

type StyleTypeProvider

type StyleTypeProvider interface {
	StyleType() string
}

StyleTypeProvider overrides the selector type for a widget.

type SubBuffer

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

SubBuffer returns a view into a rectangular region of the buffer. Writes to the SubBuffer are translated and clipped to the region.

func (*SubBuffer) Clear

func (s *SubBuffer) Clear()

Clear fills the sub-buffer region with spaces.

func (*SubBuffer) Fill

func (s *SubBuffer) Fill(r Rect, ch rune, style backend.Style)

Fill fills a region relative to the sub-buffer.

func (*SubBuffer) Set

func (s *SubBuffer) Set(x, y int, r rune, style backend.Style)

Set writes a rune at position relative to the sub-buffer.

func (*SubBuffer) SetString

func (s *SubBuffer) SetString(x, y int, str string, style backend.Style)

SetString writes a string at position relative to the sub-buffer.

func (*SubBuffer) Size

func (s *SubBuffer) Size() (w, h int)

Size returns the sub-buffer dimensions.

type Submit

type Submit struct {
	Text string
}

Submit indicates text was submitted (e.g., from input widget).

func (Submit) Command

func (Submit) Command()

type TickMsg

type TickMsg struct {
	Time time.Time
}

TickMsg is sent on each frame tick for animations.

type Unbindable

type Unbindable interface {
	Unbind()
}

Unbindable widgets release app services when removed.

type UnmountHook

type UnmountHook interface {
	OnUnmountHook()
}

UnmountHook is implemented by widgets that support an onUnmount lifecycle callback. UnbindTree calls OnUnmountHook before Unbind.

type UpdateFunc

type UpdateFunc func(app *App, msg Message) bool

UpdateFunc handles a message and returns true if a render is needed.

func WithQueue

func WithQueue(queue *state.Queue, update UpdateFunc) UpdateFunc

WithQueue wraps update to flush queue on TickMsg or QueueFlushMsg. If update is nil, DefaultUpdate is used.

func WithQueuePolicy

func WithQueuePolicy(queue *state.Queue, policy QueueFlushPolicy, update UpdateFunc) UpdateFunc

WithQueuePolicy wraps update to flush queue based on policy. If update is nil, DefaultUpdate is used.

type Widget

type Widget interface {
	// Measure returns desired size given constraints.
	// This is the first pass of layout.
	Measure(constraints Constraints) Size

	// Layout assigns final position and size.
	// Widget should store this for use in Render.
	Layout(bounds Rect)

	// Render draws the widget to the buffer.
	Render(ctx RenderContext)

	// HandleMessage processes input/events.
	// Returns result indicating if handled and any commands to bubble up.
	HandleMessage(msg Message) HandleResult
}

Widget is the core interface all UI components implement.

type WidgetPool

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

WidgetPool provides pooled widget reuse with optional reset logic. Size is best-effort and intended for limiting pool growth.

func NewWidgetPool

func NewWidgetPool[T any](newFn func() T, resetFn func(T), maxSize int) *WidgetPool[T]

NewWidgetPool creates a new widget pool. maxSize <= 0 means no explicit limit.

func (*WidgetPool[T]) Acquire

func (p *WidgetPool[T]) Acquire() T

Acquire retrieves a widget instance, creating one if needed.

func (*WidgetPool[T]) MaxSize

func (p *WidgetPool[T]) MaxSize() int

MaxSize returns the configured maximum pool size.

func (*WidgetPool[T]) Release

func (p *WidgetPool[T]) Release(widget T)

Release returns a widget instance to the pool.

func (*WidgetPool[T]) Size

func (p *WidgetPool[T]) Size() int

Size returns the approximate number of pooled widgets.

Jump to

Keyboard shortcuts

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