Documentation
¶
Index ¶
- Constants
- Variables
- func AssertSnapshot(t *testing.T, widget Widget, width, height int, description ...string)
- func AssertSnapshotNamed(t *testing.T, name string, widget Widget, width, height int, ...)
- func AssertSnapshotNamedWithOptions(t *testing.T, name string, widget Widget, width, height int, opts SVGOptions, ...)
- func AssertSnapshotWithOptions(t *testing.T, widget Widget, width, height int, opts SVGOptions, ...)
- func BoolPtr(b bool) *bool
- func BufferToANSI(buf CellBuffer, width, height int) string
- func BufferToSVG(buf CellBuffer, width, height int, opts SVGOptions) string
- func CloseLogger()
- func CurrentThemeName() string
- func DarkThemeNames() []string
- func EaseInBack(t float64) float64
- func EaseInBounce(t float64) float64
- func EaseInCirc(t float64) float64
- func EaseInCubic(t float64) float64
- func EaseInElastic(t float64) float64
- func EaseInExpo(t float64) float64
- func EaseInOutBack(t float64) float64
- func EaseInOutBounce(t float64) float64
- func EaseInOutCirc(t float64) float64
- func EaseInOutCubic(t float64) float64
- func EaseInOutElastic(t float64) float64
- func EaseInOutExpo(t float64) float64
- func EaseInOutQuad(t float64) float64
- func EaseInOutQuart(t float64) float64
- func EaseInOutQuint(t float64) float64
- func EaseInOutSine(t float64) float64
- func EaseInQuad(t float64) float64
- func EaseInQuart(t float64) float64
- func EaseInQuint(t float64) float64
- func EaseInSine(t float64) float64
- func EaseLinear(t float64) float64
- func EaseOutBack(t float64) float64
- func EaseOutBounce(t float64) float64
- func EaseOutCirc(t float64) float64
- func EaseOutCubic(t float64) float64
- func EaseOutElastic(t float64) float64
- func EaseOutExpo(t float64) float64
- func EaseOutQuad(t float64) float64
- func EaseOutQuart(t float64) float64
- func EaseOutQuint(t float64) float64
- func EaseOutSine(t float64) float64
- func EnableDebugRenderCause()
- func ExtendAndRegisterTheme(newName, baseName string, opts ...ThemeOption) bool
- func FormatKeyCaret(key string) string
- func FormatKeyEmacs(key string) string
- func FormatKeyVerbose(key string) string
- func FormatKeyVim(key string) string
- func GenerateDiffSVG(expected, actual *uv.Buffer, width, height int, opts SVGOptions) string
- func GenerateGallery(comparisons []SnapshotComparison, outputPath string) error
- func InitLogger() error
- func IntPtr(n int) *int
- func LastRenderCause() string
- func LightThemeNames() []string
- func Log(format string, args ...any)
- func LogWidgetRegistry(registry *WidgetRegistry)
- func Print(widget Widget) error
- func PrintTo(w io.Writer, widget Widget) error
- func PrintWithOptions(widget Widget, opts PrintOptions) error
- func PrintWithSize(widget Widget, width, height int) error
- func Quit()
- func RegisterInterpolator[T any](interpolator Interpolator[T])
- func RegisterTheme(name string, data ThemeData)
- func RenderToBuffer(widget Widget, width, height int) *uv.Buffer
- func RenderToBufferWithSize(widget Widget, width, height int) (buf *uv.Buffer, layoutWidth, layoutHeight int)
- func RenderToPlainString(widget Widget, width, height int) string
- func RenderToString(widget Widget, width, height int) string
- func RequestFocus(id string)
- func Run(root Widget) (runErr error)
- func SaveSnapshot(widget Widget, width, height int, path string) error
- func SaveSnapshotWithOptions(widget Widget, width, height int, path string, opts SVGOptions) error
- func ScreenText() string
- func SetDebugLogging(enabled bool)
- func SetTheme(name string)
- func Snapshot(widget Widget, width, height int) string
- func SnapshotTestMain(galleryPath string)
- func SnapshotWithOptions(widget Widget, width, height int, opts SVGOptions) string
- func ThemeNames() []string
- type Alignment
- type AnchorPoint
- type AnimatedValue
- type AnimatedValueConfig
- type Animation
- func (a *Animation[T]) Advance(dt time.Duration) bool
- func (a *Animation[T]) Get() T
- func (a *Animation[T]) IsComplete() bool
- func (a *Animation[T]) IsRunning() bool
- func (a *Animation[T]) Pause()
- func (a *Animation[T]) Progress() float64
- func (a *Animation[T]) Reset()
- func (a *Animation[T]) Resume()
- func (a *Animation[T]) Start()
- func (a *Animation[T]) Stop()
- func (a *Animation[T]) Value() AnySignal[T]
- type AnimationConfig
- type AnimationController
- func (ac *AnimationController) HasActiveAnimations() bool
- func (ac *AnimationController) Register(anim Animator) *animationHandle
- func (ac *AnimationController) Stop()
- func (ac *AnimationController) Tick() <-chan time.Time
- func (ac *AnimationController) Unregister(handle *animationHandle)
- func (ac *AnimationController) Update()
- type AnimationState
- type Animator
- type AnyAnimatedValue
- func (av *AnyAnimatedValue[T]) Get() T
- func (av *AnyAnimatedValue[T]) IsAnimating() bool
- func (av *AnyAnimatedValue[T]) Peek() T
- func (av *AnyAnimatedValue[T]) Set(value T)
- func (av *AnyAnimatedValue[T]) SetImmediate(value T)
- func (av *AnyAnimatedValue[T]) Signal() AnySignal[T]
- func (av *AnyAnimatedValue[T]) Target() T
- type AnyAnimatedValueConfig
- type AnySignal
- type Autocomplete
- type AutocompleteState
- type Blurrable
- type Border
- func AsciiBorder(color ColorProvider, decorations ...BorderDecoration) Border
- func DashedBorder(color ColorProvider, decorations ...BorderDecoration) Border
- func DoubleBorder(color ColorProvider, decorations ...BorderDecoration) Border
- func HeavyBorder(color ColorProvider, decorations ...BorderDecoration) Border
- func RoundedBorder(color ColorProvider, decorations ...BorderDecoration) Border
- func SquareBorder(color ColorProvider, decorations ...BorderDecoration) Border
- type BorderCharSet
- type BorderDecoration
- func BorderSubtitle(text string) BorderDecoration
- func BorderSubtitleCenter(text string) BorderDecoration
- func BorderSubtitleCenterMarkup(markup string) BorderDecoration
- func BorderSubtitleMarkup(markup string) BorderDecoration
- func BorderSubtitleRight(text string) BorderDecoration
- func BorderSubtitleRightMarkup(markup string) BorderDecoration
- func BorderTitle(text string) BorderDecoration
- func BorderTitleCenter(text string) BorderDecoration
- func BorderTitleCenterMarkup(markup string) BorderDecoration
- func BorderTitleMarkup(markup string) BorderDecoration
- func BorderTitleRight(text string) BorderDecoration
- func BorderTitleRightMarkup(markup string) BorderDecoration
- type BorderStyle
- type Breadcrumbs
- type BuildContext
- func (ctx BuildContext) ActiveKeybinds() []Keybind
- func (ctx BuildContext) AutoID() string
- func (ctx BuildContext) Focused() Focusable
- func (ctx BuildContext) FocusedSignal() AnySignal[Focusable]
- func (ctx BuildContext) Hovered() Widget
- func (ctx BuildContext) HoveredID() string
- func (ctx BuildContext) IsDisabled() bool
- func (ctx BuildContext) IsFocused(widget Widget) bool
- func (ctx BuildContext) IsHovered(widget Widget) bool
- func (ctx BuildContext) PushChild(index int) BuildContext
- func (ctx BuildContext) RequestFocus(id string)
- func (ctx BuildContext) Theme() ThemeData
- func (ctx BuildContext) WithDisabled() BuildContext
- type Button
- func (b Button) Build(ctx BuildContext) Widget
- func (b Button) GetContentDimensions() (width, height Dimension)
- func (b Button) IsFocusable() bool
- func (b Button) Keybinds() []Keybind
- func (b Button) OnClick(event MouseEvent)
- func (b Button) OnHover(event HoverEvent)
- func (b Button) OnKey(event KeyEvent) bool
- func (b Button) OnMouseDown(event MouseEvent)
- func (b Button) OnMouseUp(event MouseEvent)
- func (b Button) WidgetID() string
- type ButtonVariant
- type CellBuffer
- type Checkbox
- func (c *Checkbox) Build(ctx BuildContext) Widget
- func (c *Checkbox) GetContentDimensions() (width, height Dimension)
- func (c *Checkbox) IsFocusable() bool
- func (c *Checkbox) Keybinds() []Keybind
- func (c *Checkbox) OnClick(event MouseEvent)
- func (c *Checkbox) OnHover(event HoverEvent)
- func (c *Checkbox) OnKey(event KeyEvent) bool
- func (c *Checkbox) OnMouseDown(event MouseEvent)
- func (c *Checkbox) OnMouseUp(event MouseEvent)
- func (c *Checkbox) WidgetID() string
- type CheckboxState
- type ChildProvider
- type Clickable
- type Color
- func (c Color) Alpha() float64
- func (c Color) AutoText() Color
- func (c Color) Blend(other Color, ratio float64) Color
- func (c Color) BlendOver(bg Color) Color
- func (c Color) ColorAt(width, height, x, y int) Color
- func (c Color) Complement() Color
- func (c Color) ContrastRatio(other Color) float64
- func (c Color) Darken(amount float64) Color
- func (c Color) Desaturate(amount float64) Color
- func (c Color) HSL() (h, s, l float64)
- func (c Color) Hex() string
- func (c Color) Invert() Color
- func (c Color) IsDark() bool
- func (c Color) IsLight() bool
- func (c Color) IsOpaque() bool
- func (c Color) IsSet() bool
- func (c Color) Lighten(amount float64) Color
- func (c Color) Luminance() float64
- func (c Color) RGB() (r, g, b uint8)
- func (c Color) Rotate(degrees float64) Color
- func (c Color) Saturate(amount float64) Color
- func (c Color) WithAlpha(a float64) Color
- type ColorProvider
- type Column
- func (c Column) Build(ctx BuildContext) Widget
- func (c Column) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (c Column) GetContentDimensions() (width, height Dimension)
- func (c Column) GetStyle() Style
- func (c Column) OnClick(event MouseEvent)
- func (c Column) OnHover(event HoverEvent)
- func (c Column) OnMouseDown(event MouseEvent)
- func (c Column) OnMouseUp(event MouseEvent)
- func (c Column) Render(ctx *RenderContext)
- func (c Column) WidgetID() string
- type CommandPalette
- type CommandPaletteItem
- type CommandPaletteLevel
- type CommandPaletteState
- func (s *CommandPaletteState) BreadcrumbPath() []string
- func (s *CommandPaletteState) Close(keepPosition bool)
- func (s *CommandPaletteState) CurrentItem() (CommandPaletteItem, bool)
- func (s *CommandPaletteState) CurrentLevel() *CommandPaletteLevel
- func (s *CommandPaletteState) IsNested() bool
- func (s *CommandPaletteState) Open()
- func (s *CommandPaletteState) PopLevel() bool
- func (s *CommandPaletteState) PushLevel(title string, items []CommandPaletteItem)
- func (s *CommandPaletteState) SetItems(items []CommandPaletteItem)
- func (s *CommandPaletteState) SetNextFocusIDOnClose(id string)
- type Constraints
- type CrossAxisAlign
- type CursorStyle
- type DecorationPosition
- type Dialog
- type Dimension
- type DimensionSet
- type Dimensioned
- type DirectoryEntry
- type DirectoryTree
- type Dock
- func (d Dock) AllChildren() []Widget
- func (d Dock) Build(ctx BuildContext) Widget
- func (d Dock) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (d Dock) GetContentDimensions() (Dimension, Dimension)
- func (d Dock) GetStyle() Style
- func (d Dock) Render(ctx *RenderContext)
- func (d Dock) WidgetID() string
- type EasingFunc
- type Edge
- type EdgeInsets
- type EmptyWidget
- type FilterMode
- type FilterOptions
- type FilterState
- type FilteredView
- type FloatCollector
- type FloatConfig
- type FloatEntry
- type FloatPosition
- type Floating
- type FocusCollector
- func (fc *FocusCollector) Collect(widget Widget, autoID string, ctx BuildContext)
- func (fc *FocusCollector) CurrentTrapID() string
- func (fc *FocusCollector) FirstFocusableIDAfter(index int) string
- func (fc *FocusCollector) Focusables() []FocusableEntry
- func (fc *FocusCollector) Len() int
- func (fc *FocusCollector) PopAncestor()
- func (fc *FocusCollector) PopTrap()
- func (fc *FocusCollector) PushAncestor(widget Widget)
- func (fc *FocusCollector) PushTrap(id string)
- func (fc *FocusCollector) Reset()
- func (fc *FocusCollector) ShouldTrackAncestor(widget Widget) bool
- type FocusManager
- func (fm *FocusManager) ActiveKeybinds() []Keybind
- func (fm *FocusManager) FocusByID(id string)
- func (fm *FocusManager) FocusNext()
- func (fm *FocusManager) FocusPrevious()
- func (fm *FocusManager) Focused() Focusable
- func (fm *FocusManager) FocusedID() string
- func (fm *FocusManager) HandleKey(event KeyEvent) bool
- func (fm *FocusManager) IsInModalTrap() bool
- func (fm *FocusManager) RestoreFocus() string
- func (fm *FocusManager) SaveFocus()
- func (fm *FocusManager) SetFocusables(focusables []FocusableEntry)
- func (fm *FocusManager) SetRootWidget(root Widget)
- type FocusTrap
- type FocusTrapper
- type Focusable
- type FocusableEntry
- type FrameAnimation
- func (fa *FrameAnimation[T]) Advance(dt time.Duration) bool
- func (fa *FrameAnimation[T]) Get() T
- func (fa *FrameAnimation[T]) Index() int
- func (fa *FrameAnimation[T]) IsRunning() bool
- func (fa *FrameAnimation[T]) Reset()
- func (fa *FrameAnimation[T]) Start()
- func (fa *FrameAnimation[T]) Stop()
- func (fa *FrameAnimation[T]) Value() AnySignal[T]
- type FrameAnimationConfig
- type Gradient
- type Highlighter
- type HighlighterFunc
- type HorizontalAlignment
- type HoverEvent
- type HoverEventType
- type Hoverable
- type Identifiable
- type InsertStrategy
- type Interpolator
- type KeyCapturer
- type KeyEvent
- type KeyHandler
- type Keybind
- type KeybindBar
- type KeybindProvider
- type LabelVariant
- type LayoutMetrics
- func (m LayoutMetrics) Box() layout.BoxModel
- func (m LayoutMetrics) ChildBounds(i int) (Rect, bool)
- func (m LayoutMetrics) ChildCount() int
- func (m LayoutMetrics) ChildHeight(i int) (int, bool)
- func (m LayoutMetrics) ChildLayout(i int) (layout.ComputedLayout, bool)
- func (m LayoutMetrics) ChildMarginBounds(i int) (Rect, bool)
- func (m LayoutMetrics) ChildY(i int) (int, bool)
- type LayoutNodeBuilder
- type LayoutObserver
- type Layoutable
- type LineHighlight
- type List
- func (l List[T]) Build(ctx BuildContext) Widget
- func (l List[T]) CursorItem() T
- func (l List[T]) GetContentDimensions() (width, height Dimension)
- func (l List[T]) GetStyle() Style
- func (l List[T]) IsFocusable() bool
- func (l List[T]) Keybinds() []Keybind
- func (l List[T]) OnBlur()
- func (l List[T]) OnClick(event MouseEvent)
- func (l List[T]) OnHover(event HoverEvent)
- func (l List[T]) OnKey(event KeyEvent) bool
- func (l List[T]) OnMouseDown(event MouseEvent)
- func (l List[T]) OnMouseUp(event MouseEvent)
- func (l List[T]) WidgetID() string
- type ListState
- func (s *ListState[T]) Append(item T)
- func (s *ListState[T]) ApplyFilter(filter *FilterState, ...) int
- func (s *ListState[T]) Clear()
- func (s *ListState[T]) ClearAnchor()
- func (s *ListState[T]) ClearSelection()
- func (s *ListState[T]) Deselect(index int)
- func (s *ListState[T]) FilteredCount() int
- func (s *ListState[T]) GetAnchor() int
- func (s *ListState[T]) GetItems() []T
- func (s *ListState[T]) HasAnchor() bool
- func (s *ListState[T]) InsertAt(index int, item T)
- func (s *ListState[T]) IsSelected(index int) bool
- func (s *ListState[T]) ItemCount() int
- func (s *ListState[T]) Prepend(item T)
- func (s *ListState[T]) RemoveAt(index int) bool
- func (s *ListState[T]) RemoveWhere(predicate func(T) bool) int
- func (s *ListState[T]) Select(index int)
- func (s *ListState[T]) SelectAll()
- func (s *ListState[T]) SelectFirst()
- func (s *ListState[T]) SelectIndex(index int)
- func (s *ListState[T]) SelectLast()
- func (s *ListState[T]) SelectNext()
- func (s *ListState[T]) SelectPrevious()
- func (s *ListState[T]) SelectRange(from, to int)
- func (s *ListState[T]) SelectedIndices() []int
- func (s *ListState[T]) SelectedItem() (T, bool)
- func (s *ListState[T]) SelectedItems() []T
- func (s *ListState[T]) SetAnchor(index int)
- func (s *ListState[T]) SetItems(items []T)
- func (s *ListState[T]) ToggleSelection(index int)
- type Logger
- type MainAxisAlign
- type MatchRange
- type MatchResult
- type Menu
- type MenuItem
- type MenuState
- type MouseDownHandler
- type MouseEvent
- type MouseMoveHandler
- type MouseUpHandler
- type Offset
- type Panic
- type Positioned
- type PrintOptions
- type ProgressBar
- func (p ProgressBar) Build(ctx BuildContext) Widget
- func (p ProgressBar) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (p ProgressBar) GetContentDimensions() (width, height Dimension)
- func (p ProgressBar) GetStyle() Style
- func (p ProgressBar) Render(ctx *RenderContext)
- func (p ProgressBar) WidgetID() string
- type Rect
- type RenderContext
- func (ctx *RenderContext) ClipBounds() Rect
- func (ctx *RenderContext) DrawBackdrop(x, y, width, height int, backdrop ColorProvider)
- func (ctx *RenderContext) DrawBorder(x, y, width, height int, border Border)
- func (ctx *RenderContext) DrawSpan(x, y int, span Span, baseStyle Style) int
- func (ctx *RenderContext) DrawStyledText(x, y int, text string, style Style)
- func (ctx *RenderContext) DrawText(x, y int, text string)
- func (ctx *RenderContext) FillRect(x, y, width, height int, bgColor Color)
- func (ctx *RenderContext) IsFocused(widget Widget) bool
- func (ctx *RenderContext) IsVisible(absX, absY int) bool
- func (ctx *RenderContext) OverflowSubContext(xOffset, yOffset, width, height int) *RenderContext
- func (ctx *RenderContext) ScrolledSubContext(xOffset, yOffset, width, height, scrollX, scrollY int) *RenderContext
- func (ctx *RenderContext) SubContext(xOffset, yOffset, width, height int) *RenderContext
- type RenderTree
- type Renderable
- type Renderer
- func (r *Renderer) FloatAt(x, y int) *FloatEntry
- func (r *Renderer) FocusableAt(x, y int) *WidgetEntry
- func (r *Renderer) HasFloats() bool
- func (r *Renderer) HasModalFloat() bool
- func (r *Renderer) ModalCount() int
- func (r *Renderer) Render(root Widget) []FocusableEntry
- func (r *Renderer) RenderWithSize(root Widget) (layoutWidth, layoutHeight int)
- func (r *Renderer) Resize(width, height int)
- func (r *Renderer) ScreenText() string
- func (r *Renderer) ScrollableAt(x, y int) *Scrollable
- func (r *Renderer) ScrollablesAt(x, y int) []*Scrollable
- func (r *Renderer) TopFloat() *FloatEntry
- func (r *Renderer) WidgetAt(x, y int) *WidgetEntry
- func (r *Renderer) WidgetByID(id string) *WidgetEntry
- type Row
- func (r Row) Build(ctx BuildContext) Widget
- func (r Row) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (r Row) GetContentDimensions() (width, height Dimension)
- func (r Row) GetStyle() Style
- func (r Row) OnClick(event MouseEvent)
- func (r Row) OnHover(event HoverEvent)
- func (r Row) OnMouseDown(event MouseEvent)
- func (r Row) OnMouseUp(event MouseEvent)
- func (r Row) Render(ctx *RenderContext)
- func (r Row) WidgetID() string
- type SVGOptions
- type ScrollState
- func (s *ScrollState) GetOffset() int
- func (s *ScrollState) GetOffsetX() int
- func (s *ScrollState) IsAtBottom() bool
- func (s *ScrollState) IsPinned() bool
- func (s *ScrollState) ScrollDown(lines int) bool
- func (s *ScrollState) ScrollLeft(cols int) bool
- func (s *ScrollState) ScrollRight(cols int) bool
- func (s *ScrollState) ScrollToBottom()
- func (s *ScrollState) ScrollToView(y, height int)
- func (s *ScrollState) ScrollUp(lines int) bool
- func (s *ScrollState) SetOffset(offset int)
- func (s *ScrollState) SetOffsetX(offset int)
- type Scrollable
- func (s Scrollable) Build(ctx BuildContext) Widget
- func (s Scrollable) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (s Scrollable) GetContentDimensions() (width, height Dimension)
- func (s Scrollable) GetStyle() Style
- func (s Scrollable) IsFocusable() bool
- func (s Scrollable) OnClick(event MouseEvent)
- func (s Scrollable) OnHover(event HoverEvent)
- func (s Scrollable) OnKey(event KeyEvent) bool
- func (s Scrollable) OnLayout(ctx BuildContext, metrics LayoutMetrics)
- func (s Scrollable) OnMouseDown(event MouseEvent)
- func (s Scrollable) OnMouseMove(event MouseEvent)
- func (s Scrollable) OnMouseUp(event MouseEvent)
- func (s Scrollable) Render(ctx *RenderContext)
- func (s Scrollable) ScrollDown(lines int) bool
- func (s Scrollable) ScrollLeft(cols int) bool
- func (s Scrollable) ScrollRight(cols int) bool
- func (s Scrollable) ScrollUp(lines int) bool
- func (s Scrollable) WidgetID() string
- type SerializedBuffer
- type SerializedCell
- type Signal
- type Size
- type SnapshotComparison
- type SnapshotStats
- type SnapshotSuite
- type Spacer
- type Span
- func BoldSpan(text string, fg ...Color) Span
- func ColorSpan(text string, fg Color) Span
- func FaintSpan(text string, fg ...Color) Span
- func HighlightSpans(text string, ranges []MatchRange, highlight SpanStyle) []Span
- func ItalicSpan(text string, fg ...Color) Span
- func ParseMarkup(markup string, theme ThemeData) []Span
- func PlainSpan(text string) Span
- func StrikethroughSpan(text string, fg ...Color) Span
- func StyledSpan(text string, style SpanStyle) Span
- func UnderlineSpan(text string, fg ...Color) Span
- type SpanStyle
- type Sparkline
- func (s Sparkline) Build(ctx BuildContext) Widget
- func (s Sparkline) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (s Sparkline) GetContentDimensions() (width, height Dimension)
- func (s Sparkline) GetStyle() Style
- func (s Sparkline) Layout(ctx BuildContext, constraints Constraints) Size
- func (s Sparkline) Render(ctx *RenderContext)
- func (s Sparkline) WidgetID() string
- type Spinner
- type SpinnerState
- type SpinnerStyle
- type SplitPane
- func (s SplitPane) Build(ctx BuildContext) Widget
- func (s SplitPane) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (s SplitPane) ChildWidgets() []Widget
- func (s SplitPane) GetContentDimensions() (width, height Dimension)
- func (s SplitPane) GetStyle() Style
- func (s SplitPane) IsFocusable() bool
- func (s SplitPane) Keybinds() []Keybind
- func (s SplitPane) OnClick(event MouseEvent)
- func (s SplitPane) OnHover(event HoverEvent)
- func (s SplitPane) OnKey(event KeyEvent) bool
- func (s SplitPane) OnLayout(ctx BuildContext, metrics LayoutMetrics)
- func (s SplitPane) OnMouseDown(event MouseEvent)
- func (s SplitPane) OnMouseMove(event MouseEvent)
- func (s SplitPane) OnMouseUp(event MouseEvent)
- func (s SplitPane) Render(ctx *RenderContext)
- func (s SplitPane) WidgetID() string
- type SplitPaneOrientation
- type SplitPaneState
- type Stack
- func (s Stack) AllChildren() []Widget
- func (s Stack) Build(ctx BuildContext) Widget
- func (s Stack) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (s Stack) GetContentDimensions() (width, height Dimension)
- func (s Stack) GetStyle() Style
- func (s Stack) OnClick(event MouseEvent)
- func (s Stack) OnHover(event HoverEvent)
- func (s Stack) OnMouseDown(event MouseEvent)
- func (s Stack) OnMouseUp(event MouseEvent)
- func (s Stack) Render(ctx *RenderContext)
- func (s Stack) WidgetID() string
- type Style
- type Styled
- type Suggestion
- type Switcher
- type Tab
- type TabBar
- func (t TabBar) Build(ctx BuildContext) Widget
- func (t TabBar) GetDimensions() (width, height Dimension)
- func (t TabBar) GetStyle() Style
- func (t TabBar) IsFocusable() bool
- func (t TabBar) Keybinds() []Keybind
- func (t TabBar) OnClick(event MouseEvent)
- func (t TabBar) OnHover(event HoverEvent)
- func (t TabBar) OnKey(event KeyEvent) bool
- func (t TabBar) OnMouseDown(event MouseEvent)
- func (t TabBar) OnMouseUp(event MouseEvent)
- func (t TabBar) WidgetID() string
- type TabKeybindPattern
- type TabState
- func (s *TabState) ActiveIndex() int
- func (s *TabState) ActiveKey() string
- func (s *TabState) ActiveKeyPeek() string
- func (s *TabState) ActiveTab() *Tab
- func (s *TabState) AddTab(tab Tab)
- func (s *TabState) EditingKey() string
- func (s *TabState) InsertTab(index int, tab Tab)
- func (s *TabState) IsEditing(key string) bool
- func (s *TabState) MoveTabLeft(key string) bool
- func (s *TabState) MoveTabRight(key string) bool
- func (s *TabState) RemoveTab(key string) bool
- func (s *TabState) SelectIndex(index int)
- func (s *TabState) SelectNext()
- func (s *TabState) SelectPrevious()
- func (s *TabState) SetActiveKey(key string)
- func (s *TabState) SetLabel(key, label string)
- func (s *TabState) StartEditing(key string)
- func (s *TabState) StopEditing()
- func (s *TabState) TabCount() int
- func (s *TabState) Tabs() []Tab
- func (s *TabState) TabsPeek() []Tab
- type TabView
- type Table
- func (t Table[T]) Build(ctx BuildContext) Widget
- func (t Table[T]) CursorRow() T
- func (t Table[T]) GetContentDimensions() (width, height Dimension)
- func (t Table[T]) GetStyle() Style
- func (t Table[T]) IsFocusable() bool
- func (t Table[T]) Keybinds() []Keybind
- func (t Table[T]) OnClick(event MouseEvent)
- func (t Table[T]) OnHover(event HoverEvent)
- func (t Table[T]) OnKey(event KeyEvent) bool
- func (t Table[T]) OnMouseDown(event MouseEvent)
- func (t Table[T]) OnMouseUp(event MouseEvent)
- func (t Table[T]) WidgetID() string
- type TableColumn
- type TableSelectionMode
- type TableState
- func (s *TableState[T]) Append(row T)
- func (s *TableState[T]) Clear()
- func (s *TableState[T]) ClearAnchor()
- func (s *TableState[T]) ClearSelection()
- func (s *TableState[T]) Deselect(index int)
- func (s *TableState[T]) GetAnchor() int
- func (s *TableState[T]) GetRows() []T
- func (s *TableState[T]) HasAnchor() bool
- func (s *TableState[T]) InsertAt(index int, row T)
- func (s *TableState[T]) IsSelected(index int) bool
- func (s *TableState[T]) Prepend(row T)
- func (s *TableState[T]) RemoveAt(index int) bool
- func (s *TableState[T]) RemoveWhere(predicate func(T) bool) int
- func (s *TableState[T]) RowCount() int
- func (s *TableState[T]) Select(index int)
- func (s *TableState[T]) SelectAll()
- func (s *TableState[T]) SelectColumn(index int)
- func (s *TableState[T]) SelectFirst()
- func (s *TableState[T]) SelectIndex(index int)
- func (s *TableState[T]) SelectLast()
- func (s *TableState[T]) SelectNext()
- func (s *TableState[T]) SelectPrevious()
- func (s *TableState[T]) SelectRange(from, to int)
- func (s *TableState[T]) SelectedIndices() []int
- func (s *TableState[T]) SelectedRow() (T, bool)
- func (s *TableState[T]) SelectedRows() []T
- func (s *TableState[T]) SetAnchor(index int)
- func (s *TableState[T]) SetRows(rows []T)
- func (s *TableState[T]) ToggleSelection(index int)
- type Text
- func (t Text) Build(ctx BuildContext) Widget
- func (t Text) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (t Text) GetContentDimensions() (width, height Dimension)
- func (t Text) GetStyle() Style
- func (t Text) OnClick(event MouseEvent)
- func (t Text) OnHover(event HoverEvent)
- func (t Text) OnMouseDown(event MouseEvent)
- func (t Text) OnMouseUp(event MouseEvent)
- func (t Text) Render(ctx *RenderContext)
- func (t Text) WidgetID() string
- type TextAlign
- type TextArea
- func (t TextArea) Build(ctx BuildContext) Widget
- func (t TextArea) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (t TextArea) CapturesKey(key string) bool
- func (t TextArea) GetContentDimensions() (width, height Dimension)
- func (t TextArea) GetStyle() Style
- func (t TextArea) IsFocusable() bool
- func (t TextArea) Keybinds() []Keybind
- func (t TextArea) Layout(ctx BuildContext, constraints Constraints) Size
- func (t TextArea) OnBlur()
- func (t TextArea) OnClick(event MouseEvent)
- func (t TextArea) OnHover(event HoverEvent)
- func (t TextArea) OnKey(event KeyEvent) bool
- func (t TextArea) OnMouseDown(event MouseEvent)
- func (t TextArea) OnMouseMove(event MouseEvent)
- func (t TextArea) OnMouseUp(event MouseEvent)
- func (t TextArea) Render(ctx *RenderContext)
- func (t TextArea) WidgetID() string
- type TextAreaState
- func (s *TextAreaState) ClearSelection()
- func (s *TextAreaState) CursorDown()
- func (s *TextAreaState) CursorDownBy(lines int)
- func (s *TextAreaState) CursorEnd()
- func (s *TextAreaState) CursorHome()
- func (s *TextAreaState) CursorLeft()
- func (s *TextAreaState) CursorRight()
- func (s *TextAreaState) CursorScreenPosition(widgetX, widgetY int) (screenX, screenY int)
- func (s *TextAreaState) CursorUp()
- func (s *TextAreaState) CursorUpBy(lines int)
- func (s *TextAreaState) CursorWordLeft()
- func (s *TextAreaState) CursorWordRight()
- func (s *TextAreaState) DeleteBackward()
- func (s *TextAreaState) DeleteForward()
- func (s *TextAreaState) DeleteSelection() bool
- func (s *TextAreaState) DeleteToBeginning()
- func (s *TextAreaState) DeleteToEnd()
- func (s *TextAreaState) DeleteWordBackward()
- func (s *TextAreaState) GetSelectedText() string
- func (s *TextAreaState) GetSelectionBounds() (start, end int)
- func (s *TextAreaState) GetText() string
- func (s *TextAreaState) HasSelection() bool
- func (s *TextAreaState) Insert(text string)
- func (s *TextAreaState) InsertNewline()
- func (s *TextAreaState) ReplaceSelection(text string)
- func (s *TextAreaState) SelectAll()
- func (s *TextAreaState) SelectLine(index int)
- func (s *TextAreaState) SelectWord(index int)
- func (s *TextAreaState) SetCursorFromLocalPosition(localX, localY int, contentWidth int)
- func (s *TextAreaState) SetSelectionAnchor(index int)
- func (s *TextAreaState) SetText(text string)
- func (s *TextAreaState) ToggleWrap()
- type TextHighlight
- type TextInput
- func (t TextInput) Build(ctx BuildContext) Widget
- func (t TextInput) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (t TextInput) CapturesKey(key string) bool
- func (t TextInput) CursorScreenPosition(widgetX int) int
- func (t TextInput) GetContentDimensions() (width, height Dimension)
- func (t TextInput) GetStyle() Style
- func (t TextInput) IsFocusable() bool
- func (t TextInput) Keybinds() []Keybind
- func (t TextInput) Layout(ctx BuildContext, constraints Constraints) Size
- func (t TextInput) OnBlur()
- func (t TextInput) OnClick(event MouseEvent)
- func (t TextInput) OnHover(event HoverEvent)
- func (t TextInput) OnKey(event KeyEvent) bool
- func (t TextInput) OnMouseDown(event MouseEvent)
- func (t TextInput) OnMouseMove(event MouseEvent)
- func (t TextInput) OnMouseUp(event MouseEvent)
- func (t TextInput) Render(ctx *RenderContext)
- func (t TextInput) WidgetID() string
- type TextInputState
- func (s *TextInputState) ClearSelection()
- func (s *TextInputState) CursorEnd()
- func (s *TextInputState) CursorHome()
- func (s *TextInputState) CursorLeft()
- func (s *TextInputState) CursorRight()
- func (s *TextInputState) CursorWordLeft()
- func (s *TextInputState) CursorWordRight()
- func (s *TextInputState) DeleteBackward()
- func (s *TextInputState) DeleteForward()
- func (s *TextInputState) DeleteSelection() bool
- func (s *TextInputState) DeleteToBeginning()
- func (s *TextInputState) DeleteToEnd()
- func (s *TextInputState) DeleteWordBackward()
- func (s *TextInputState) GetSelectedText() string
- func (s *TextInputState) GetSelectionBounds() (start, end int)
- func (s *TextInputState) GetText() string
- func (s *TextInputState) HasSelection() bool
- func (s *TextInputState) Insert(text string)
- func (s *TextInputState) ReplaceSelection(text string)
- func (s *TextInputState) SelectAll()
- func (s *TextInputState) SelectWord(index int)
- func (s *TextInputState) SetCursorFromLocalPosition(localX int)
- func (s *TextInputState) SetSelectionAnchor(index int)
- func (s *TextInputState) SetText(text string)
- type ThemeData
- type ThemeOption
- func WithAccent(c Color) ThemeOption
- func WithActiveCursor(c Color) ThemeOption
- func WithBackground(c Color) ThemeOption
- func WithBorder(c Color) ThemeOption
- func WithCursor(c Color) ThemeOption
- func WithError(c Color) ThemeOption
- func WithFocusRing(c Color) ThemeOption
- func WithInfo(c Color) ThemeOption
- func WithIsLight(isLight bool) ThemeOption
- func WithLink(c Color) ThemeOption
- func WithOverlay(c Color) ThemeOption
- func WithPlaceholder(c Color) ThemeOption
- func WithPrimary(c Color) ThemeOption
- func WithScrollbarThumb(c Color) ThemeOption
- func WithScrollbarTrack(c Color) ThemeOption
- func WithSecondary(c Color) ThemeOption
- func WithSelection(c Color) ThemeOption
- func WithSelectionText(c Color) ThemeOption
- func WithSuccess(c Color) ThemeOption
- func WithSurface(c Color) ThemeOption
- func WithSurface2(c Color) ThemeOption
- func WithSurface3(c Color) ThemeOption
- func WithSurfaceHover(c Color) ThemeOption
- func WithText(c Color) ThemeOption
- func WithTextDisabled(c Color) ThemeOption
- func WithTextMuted(c Color) ThemeOption
- func WithTextOnAccent(c Color) ThemeOption
- func WithTextOnError(c Color) ThemeOption
- func WithTextOnInfo(c Color) ThemeOption
- func WithTextOnPrimary(c Color) ThemeOption
- func WithTextOnSecondary(c Color) ThemeOption
- func WithTextOnSuccess(c Color) ThemeOption
- func WithTextOnWarning(c Color) ThemeOption
- func WithWarning(c Color) ThemeOption
- type Tooltip
- type TooltipPosition
- type Tree
- func (t Tree[T]) Build(ctx BuildContext) Widget
- func (t Tree[T]) GetDimensions() (width, height Dimension)
- func (t Tree[T]) GetStyle() Style
- func (t Tree[T]) IsFocusable() bool
- func (t Tree[T]) Keybinds() []Keybind
- func (t Tree[T]) OnKey(event KeyEvent) bool
- func (t Tree[T]) OnMouseDown(event MouseEvent)
- func (t Tree[T]) WidgetID() string
- type TreeNode
- type TreeNodeContext
- type TreeState
- func (s *TreeState[T]) ClearSelection()
- func (s *TreeState[T]) Collapse(path []int)
- func (s *TreeState[T]) CollapseAll()
- func (s *TreeState[T]) CursorDown()
- func (s *TreeState[T]) CursorNode() (T, bool)
- func (s *TreeState[T]) CursorToFirstChild()
- func (s *TreeState[T]) CursorToParent()
- func (s *TreeState[T]) CursorUp()
- func (s *TreeState[T]) Deselect(path []int)
- func (s *TreeState[T]) Expand(path []int)
- func (s *TreeState[T]) ExpandAll()
- func (s *TreeState[T]) IsCollapsed(path []int) bool
- func (s *TreeState[T]) IsSelected(path []int) bool
- func (s *TreeState[T]) NodeAtPath(path []int) (TreeNode[T], bool)
- func (s *TreeState[T]) Select(path []int)
- func (s *TreeState[T]) SelectedPaths() [][]int
- func (s *TreeState[T]) SetChildren(path []int, children []TreeNode[T])
- func (s *TreeState[T]) Toggle(path []int)
- func (s *TreeState[T]) ToggleSelection(path []int)
- type UnderlineStyle
- type VerticalAlignment
- type Widget
- func DisabledWhen(condition bool, child Widget) Widget
- func EnabledWhen(condition bool, child Widget) Widget
- func HideWhen(condition bool, child Widget) Widget
- func Inert(child Widget) Widget
- func InvisibleWhen(condition bool, child Widget) Widget
- func ShowWhen(condition bool, child Widget) Widget
- func VisibleWhen(condition bool, child Widget) Widget
- type WidgetEntry
- type WidgetRegistry
- func (r *WidgetRegistry) Entries() []WidgetEntry
- func (r *WidgetRegistry) FocusableAt(x, y int) *WidgetEntry
- func (r *WidgetRegistry) IncrementTotal()
- func (r *WidgetRegistry) Record(widget Widget, eventWidget Widget, id string, bounds Rect)
- func (r *WidgetRegistry) Reset()
- func (r *WidgetRegistry) ScrollableAt(x, y int) *Scrollable
- func (r *WidgetRegistry) ScrollablesAt(x, y int) []*Scrollable
- func (r *WidgetRegistry) TotalCount() int
- func (r *WidgetRegistry) WidgetAt(x, y int) *WidgetEntry
- func (r *WidgetRegistry) WidgetByID(id string) *WidgetEntry
- type WrapMode
Constants ¶
const ( Top = layout.DockTop Bottom = layout.DockBottom Left = layout.DockLeft Right = layout.DockRight )
Edge constants for dock order.
const ( // Dark themes ThemeNameRosePine = "rose-pine" ThemeNameDracula = "dracula" ThemeNameTokyoNight = "tokyo-night" ThemeNameCatppuccin = "catppuccin" ThemeNameGruvbox = "gruvbox" ThemeNameNord = "nord" ThemeNameSolarized = "solarized" ThemeNameKanagawa = "kanagawa" ThemeNameMonokai = "monokai" ThemeNameGalaxy = "galaxy" ThemeNameAurora = "aurora" ThemeNameObsidianTide = "obsidian-tide" ThemeNameMidnightEmber = "midnight-ember" ThemeNameHearthstone = "hearthstone" ThemeNameCyberdeck = "cyberdeck" ThemeNameNeonReef = "neon-reef" ThemeNameUnderstory = "understory" ThemeNameDwarven = "dwarven" ThemeNameAbyss = "abyss" ThemeNameAmber = "amber" ThemeNameVelvet = "velvet" ThemeNamePhosphor = "phosphor" // Light themes ThemeNameRosePineDawn = "rose-pine-dawn" ThemeNameDraculaLight = "dracula-light" ThemeNameTokyoNightDay = "tokyo-night-day" ThemeNameCatppuccinLatte = "catppuccin-latte" ThemeNameGruvboxLight = "gruvbox-light" ThemeNameNordLight = "nord-light" ThemeNameSolarizedLight = "solarized-light" ThemeNameKanagawaLotus = "kanagawa-lotus" ThemeNameMonokaiLight = "monokai-light" )
Theme name constants for built-in themes
const DefaultSelectionAlpha = 0.25
Variables ¶
var ( AlignTopStart = Alignment{HAlignStart, VAlignTop} AlignTopCenter = Alignment{HAlignCenter, VAlignTop} AlignTopEnd = Alignment{HAlignEnd, VAlignTop} AlignCenterStart = Alignment{HAlignStart, VAlignCenter} AlignCenter = Alignment{HAlignCenter, VAlignCenter} AlignCenterEnd = Alignment{HAlignEnd, VAlignCenter} AlignBottomStart = Alignment{HAlignStart, VAlignBottom} AlignBottomCenter = Alignment{HAlignCenter, VAlignBottom} AlignBottomEnd = Alignment{HAlignEnd, VAlignBottom} )
Predefined alignments for common positioning patterns.
var ( Black = RGB(0, 0, 0) Red = RGB(170, 0, 0) Green = RGB(0, 170, 0) Yellow = RGB(170, 170, 0) Blue = RGB(0, 0, 170) Magenta = RGB(170, 0, 170) Cyan = RGB(0, 170, 170) White = RGB(170, 170, 170) BrightBlack = RGB(85, 85, 85) BrightRed = RGB(255, 85, 85) BrightGreen = RGB(85, 255, 85) BrightYellow = RGB(255, 255, 85) BrightBlue = RGB(85, 85, 255) BrightMagenta = RGB(255, 85, 255) BrightCyan = RGB(85, 255, 255) BrightWhite = RGB(255, 255, 255) )
ANSI color constants (backwards compatible names with true color values).
var ( // SpinnerDots is the classic braille dots spinner. SpinnerDots = SpinnerStyle{ Frames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}, FrameTime: 80 * time.Millisecond, } // SpinnerLine is a simple rotating line spinner. SpinnerLine = SpinnerStyle{ Frames: []string{"-", "\\", "|", "/"}, FrameTime: 100 * time.Millisecond, } // SpinnerCircle is a quarter-filled circle spinner. SpinnerCircle = SpinnerStyle{ Frames: []string{"◐", "◓", "◑", "◒"}, FrameTime: 120 * time.Millisecond, } // SpinnerBounce is a bouncing dot spinner. SpinnerBounce = SpinnerStyle{ Frames: []string{"⠁", "⠂", "⠄", "⠂"}, FrameTime: 120 * time.Millisecond, } // SpinnerArrow is a rotating arrow spinner. SpinnerArrow = SpinnerStyle{ Frames: []string{"←", "↖", "↑", "↗", "→", "↘", "↓", "↙"}, FrameTime: 100 * time.Millisecond, } // SpinnerBraille is a detailed braille pattern spinner. SpinnerBraille = SpinnerStyle{ Frames: []string{"⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"}, FrameTime: 80 * time.Millisecond, } // SpinnerGrow is a growing bar spinner. SpinnerGrow = SpinnerStyle{ Frames: []string{"▁", "▂", "▃", "▄", "▅", "▆", "▇", "█", "▇", "▆", "▅", "▄", "▃", "▂"}, FrameTime: 80 * time.Millisecond, } // SpinnerPulse is a pulsing block spinner. SpinnerPulse = SpinnerStyle{ Frames: []string{"█", "▓", "▒", "░", "▒", "▓"}, FrameTime: 100 * time.Millisecond, } // SpinnerClock is a clock-like spinner. SpinnerClock = SpinnerStyle{ Frames: []string{"🕐", "🕑", "🕒", "🕓", "🕔", "🕕", "🕖", "🕗", "🕘", "🕙", "🕚", "🕛"}, FrameTime: 100 * time.Millisecond, } // SpinnerMoon is a moon phase spinner. SpinnerMoon = SpinnerStyle{ Frames: []string{"🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘"}, FrameTime: 120 * time.Millisecond, } // SpinnerDotsBounce is a horizontal bouncing dots spinner. SpinnerDotsBounce = SpinnerStyle{ Frames: []string{"⠁", "⠂", "⠄", "⡀", "⢀", "⠠", "⠐", "⠈"}, FrameTime: 100 * time.Millisecond, } )
Built-in spinner styles.
var Auto = Dimension{/* contains filtered or unexported fields */}
Auto represents an auto-sizing dimension that fits content. Note: Auto has value=1 to distinguish it from the zero value (unset).
var DefaultModalBackdropColor = RGBA(0, 0, 0, 0.5)
DefaultModalBackdropColor is the default backdrop color for modal floats. Semi-transparent black at 50% opacity.
var ErrPanicked = errors.New("terma: application panicked (see stderr for details)")
ErrPanicked is returned by Run when the application panicked. The detailed panic message is printed to stderr.
Functions ¶
func AssertSnapshot ¶
AssertSnapshot renders a widget and compares it against a golden file.
The golden file is stored in testdata/<TestName>.svg relative to the test file. If the file doesn't exist or UPDATE_SNAPSHOTS=1 is set, the file is created/updated.
All failures are collected and can be viewed in a combined gallery by calling SnapshotTestMain from your TestMain function.
An optional description can be provided to explain what should be visible in the snapshot. This description appears in the gallery to help reviewers understand what they're looking at.
Example:
func TestMyWidget(t *testing.T) {
widget := Text{Content: "Hello"}
AssertSnapshot(t, widget, 20, 5, "White 'Hello' text left-aligned at top-left corner")
}
To update golden files after intentional changes:
UPDATE_SNAPSHOTS=1 go test ./...
func AssertSnapshotNamed ¶
func AssertSnapshotNamed(t *testing.T, name string, widget Widget, width, height int, description ...string)
AssertSnapshotNamed renders a widget and compares against a golden file with a custom name. Use this when you need multiple snapshots in a single test. An optional description can be provided to explain what should be visible in the snapshot.
Example:
func TestMyWidget(t *testing.T) {
AssertSnapshotNamed(t, "initial", widget, 20, 5, "Widget in initial state")
widget.Update()
AssertSnapshotNamed(t, "after_update", widget, 20, 5, "Widget after state change")
}
func AssertSnapshotNamedWithOptions ¶
func AssertSnapshotNamedWithOptions(t *testing.T, name string, widget Widget, width, height int, opts SVGOptions, description ...string)
AssertSnapshotNamedWithOptions renders a widget with custom options and compares against a named golden file. An optional description can be provided to explain what should be visible in the snapshot.
func AssertSnapshotWithOptions ¶
func AssertSnapshotWithOptions(t *testing.T, widget Widget, width, height int, opts SVGOptions, description ...string)
AssertSnapshotWithOptions renders a widget with custom SVG options and compares against a golden file. An optional description can be provided to explain what should be visible in the snapshot.
func BufferToANSI ¶
func BufferToANSI(buf CellBuffer, width, height int) string
BufferToANSI converts a rendered buffer to an ANSI-styled string.
func BufferToSVG ¶
func BufferToSVG(buf CellBuffer, width, height int, opts SVGOptions) string
BufferToSVG converts a cell buffer to an SVG string.
func CurrentThemeName ¶
func CurrentThemeName() string
CurrentThemeName returns the name of the currently active theme.
func DarkThemeNames ¶
func DarkThemeNames() []string
DarkThemeNames returns a slice of all registered dark theme names in alphabetical order.
func EaseInCubic ¶
EaseInCubic starts slow and accelerates (cubic).
func EaseInElastic ¶
EaseInElastic provides elastic effect at the start.
func EaseInExpo ¶
EaseInExpo starts very slow with exponential acceleration.
func EaseInOutBack ¶
EaseInOutBack overshoots slightly at both ends.
func EaseInOutBounce ¶
EaseInOutBounce bounces at both ends.
func EaseInOutCirc ¶
EaseInOutCirc accelerates then decelerates with circular motion.
func EaseInOutCubic ¶
EaseInOutCubic accelerates then decelerates (cubic).
func EaseInOutElastic ¶
EaseInOutElastic provides elastic effect at both ends.
func EaseInOutExpo ¶
EaseInOutExpo accelerates then decelerates exponentially.
func EaseInOutQuad ¶
EaseInOutQuad accelerates then decelerates (quadratic).
func EaseInOutQuart ¶
EaseInOutQuart accelerates then decelerates (quartic).
func EaseInOutQuint ¶
EaseInOutQuint accelerates then decelerates (quintic).
func EaseInOutSine ¶
EaseInOutSine accelerates then decelerates using sine curve.
func EaseInQuad ¶
EaseInQuad starts slow and accelerates (quadratic).
func EaseInQuart ¶
EaseInQuart starts slow and accelerates (quartic).
func EaseInQuint ¶
EaseInQuint starts slow and accelerates (quintic).
func EaseLinear ¶
EaseLinear provides no easing (constant velocity).
func EaseOutCirc ¶
EaseOutCirc decelerates with circular motion.
func EaseOutCubic ¶
EaseOutCubic starts fast and decelerates (cubic).
func EaseOutElastic ¶
EaseOutElastic provides elastic effect at the end.
func EaseOutQuad ¶
EaseOutQuad starts fast and decelerates (quadratic).
func EaseOutQuart ¶
EaseOutQuart starts fast and decelerates (quartic).
func EaseOutQuint ¶
EaseOutQuint starts fast and decelerates (quintic).
func EnableDebugRenderCause ¶
func EnableDebugRenderCause()
EnableDebugRenderCause turns on tracking of the most recent render cause.
func ExtendAndRegisterTheme ¶
func ExtendAndRegisterTheme(newName, baseName string, opts ...ThemeOption) bool
ExtendAndRegisterTheme extends a theme and registers it in one call. Returns false if base theme not found.
func FormatKeyCaret ¶
FormatKeyCaret formats keys in classic Unix caret notation. ctrl+x → ^X, other modifiers fall back to verbose style.
Examples:
- "ctrl+c" → "^C"
- "ctrl+x" → "^X"
- "shift+tab" → "Shift+Tab"
- "enter" → "Enter"
- " " → "Space"
func FormatKeyEmacs ¶
FormatKeyEmacs formats keys in Emacs style. ctrl → C-, alt/meta → M-, shift → S-
Examples:
- "ctrl+x" → "C-x"
- "alt+x" → "M-x"
- "ctrl+alt+x" → "C-M-x"
- "shift+tab" → "S-TAB"
- "enter" → "RET"
- " " → "SPC"
func FormatKeyVerbose ¶
FormatKeyVerbose formats keys in readable title case.
Examples:
- "ctrl+x" → "Ctrl+X"
- "shift+tab" → "Shift+Tab"
- "enter" → "Enter"
- " " → "Space"
func FormatKeyVim ¶
FormatKeyVim formats keys in Vim style. Keys are wrapped in angle brackets with modifier prefixes.
Examples:
- "ctrl+x" → "<C-x>"
- "alt+x" → "<M-x>"
- "shift+tab" → "<S-Tab>"
- "enter" → "<CR>"
- " " → "<Space>"
func GenerateDiffSVG ¶
func GenerateDiffSVG(expected, actual *uv.Buffer, width, height int, opts SVGOptions) string
GenerateDiffSVG creates an SVG highlighting cells that differ between two buffers. Matching cells are shown dimmed, differing cells are highlighted in bright magenta.
func GenerateGallery ¶
func GenerateGallery(comparisons []SnapshotComparison, outputPath string) error
GenerateGallery creates an HTML page comparing actual vs expected snapshots.
func InitLogger ¶
func InitLogger() error
InitLogger initializes the global logger. Call this at the start of your application to enable logging.
func IntPtr ¶
IntPtr returns a pointer to an int value. This is a helper for creating Positioned widgets.
func LastRenderCause ¶
func LastRenderCause() string
LastRenderCause returns a debug string describing the most recent render cause.
func LightThemeNames ¶
func LightThemeNames() []string
LightThemeNames returns a slice of all registered light theme names in alphabetical order.
func LogWidgetRegistry ¶
func LogWidgetRegistry(registry *WidgetRegistry)
LogWidgetRegistry logs all entries in a widget registry.
func Print ¶
Print renders a widget to stdout with ANSI styling. Auto-detects terminal dimensions or falls back to 80x24. Output height is determined by the widget's computed layout.
func PrintWithOptions ¶
func PrintWithOptions(widget Widget, opts PrintOptions) error
PrintWithOptions renders a widget using custom options.
func PrintWithSize ¶
PrintWithSize renders a widget to stdout at specific dimensions.
func Quit ¶
func Quit()
Quit exits the running application gracefully. This performs the same teardown as pressing Ctrl+C.
func RegisterInterpolator ¶
func RegisterInterpolator[T any](interpolator Interpolator[T])
RegisterInterpolator registers a custom interpolator for type T. Built-in types (float64, float32, int, int64, Color) are registered automatically.
func RegisterTheme ¶
RegisterTheme registers a custom theme with the given name. If a theme with this name already exists, it is replaced. If this is the currently active theme, the change takes effect immediately.
func RenderToBuffer ¶
RenderToBuffer renders a widget to a headless buffer. The returned buffer can be inspected with CellAt() or converted to SVG.
func RenderToBufferWithSize ¶
func RenderToBufferWithSize(widget Widget, width, height int) (buf *uv.Buffer, layoutWidth, layoutHeight int)
RenderToBufferWithSize renders a widget to a headless buffer and returns the widget's computed border-box dimensions (outer size including padding and borders). This is useful for auto-sizing output where you want to know how much space the widget actually occupies, not just the buffer size.
The first focusable widget is automatically focused so that cursor/focus styling is visible in the rendered output.
func RenderToPlainString ¶
RenderToPlainString renders a widget to a plain text string (no ANSI codes). Uses the widget's computed layout dimensions (border-box size).
func RenderToString ¶
RenderToString renders a widget to an ANSI-styled string. Uses the widget's computed layout dimensions (border-box size).
func RequestFocus ¶
func RequestFocus(id string)
RequestFocus requests that the widget with the given ID receive focus after the current render cycle completes. This can be called from anywhere, such as keybind actions or callbacks.
func Run ¶
Run starts the application with the given root widget and blocks until it exits. The root widget can implement KeyHandler to receive key events that bubble up from focused descendants.
func SaveSnapshot ¶
SaveSnapshot renders a widget and writes the SVG to a file.
func SaveSnapshotWithOptions ¶
func SaveSnapshotWithOptions(widget Widget, width, height int, path string, opts SVGOptions) error
SaveSnapshotWithOptions renders a widget and writes the SVG to a file with custom options.
func ScreenText ¶
func ScreenText() string
ScreenText returns the current screen content as plain text. Returns empty string if no app is running.
func SetDebugLogging ¶
func SetDebugLogging(enabled bool)
SetDebugLogging enables or disables debug logging. Logging is enabled by default when InitLogger is called.
func SetTheme ¶
func SetTheme(name string)
SetTheme switches to the theme with the given name. If the theme is not found, this logs a warning and does nothing.
func SnapshotTestMain ¶
func SnapshotTestMain(galleryPath string)
SnapshotTestMain generates a gallery of all snapshot comparisons. Call this from TestMain after m.Run() completes.
Example:
func TestMain(m *testing.M) {
code := m.Run()
terma.SnapshotTestMain("testdata/snapshot_gallery.html")
os.Exit(code)
}
func SnapshotWithOptions ¶
func SnapshotWithOptions(widget Widget, width, height int, opts SVGOptions) string
SnapshotWithOptions renders a widget and returns SVG with custom options.
func ThemeNames ¶
func ThemeNames() []string
ThemeNames returns a slice of all registered theme names in alphabetical order.
Types ¶
type Alignment ¶
type Alignment struct {
Horizontal HorizontalAlignment
Vertical VerticalAlignment
}
Alignment combines horizontal and vertical alignment for 2D positioning.
type AnchorPoint ¶
type AnchorPoint int
AnchorPoint specifies where on an anchor widget to attach a floating widget.
const ( // AnchorUnset indicates no explicit anchor was set. AnchorUnset AnchorPoint = iota // AnchorTopLeft positions the float at the top-left of the anchor. AnchorTopLeft // AnchorTopCenter positions the float at the top-center of the anchor. AnchorTopCenter // AnchorTopRight positions the float at the top-right of the anchor. AnchorTopRight // AnchorBottomLeft positions the float below the anchor, aligned to its left edge. AnchorBottomLeft // AnchorBottomCenter positions the float below the anchor, centered. AnchorBottomCenter // AnchorBottomRight positions the float below the anchor, aligned to its right edge. AnchorBottomRight // AnchorLeftTop positions the float to the left of the anchor, aligned to its top. AnchorLeftTop // AnchorLeftCenter positions the float to the left of the anchor, centered vertically. AnchorLeftCenter // AnchorLeftBottom positions the float to the left of the anchor, aligned to its bottom. AnchorLeftBottom // AnchorRightTop positions the float to the right of the anchor, aligned to its top. AnchorRightTop // AnchorRightCenter positions the float to the right of the anchor, centered vertically. AnchorRightCenter // AnchorRightBottom positions the float to the right of the anchor, aligned to its bottom. AnchorRightBottom )
type AnimatedValue ¶
type AnimatedValue[T comparable] struct { // contains filtered or unexported fields }
AnimatedValue wraps a value and animates transitions when Set() is called. It provides a signal-like interface but smoothly transitions between values. When Set() is called multiple times rapidly, the animation retargets from the current interpolated position to the new target for smooth motion.
func NewAnimatedValue ¶
func NewAnimatedValue[T comparable](config AnimatedValueConfig[T]) *AnimatedValue[T]
NewAnimatedValue creates a new animated value. Panics if no interpolator is registered for type T and none is provided in config.
func (*AnimatedValue[T]) Get ¶
func (av *AnimatedValue[T]) Get() T
Get returns the current animated value. During Build(), this subscribes the widget to updates.
func (*AnimatedValue[T]) IsAnimating ¶
func (av *AnimatedValue[T]) IsAnimating() bool
IsAnimating returns true if an animation is in progress.
func (*AnimatedValue[T]) Peek ¶
func (av *AnimatedValue[T]) Peek() T
Peek returns the current value without subscribing.
func (*AnimatedValue[T]) Set ¶
func (av *AnimatedValue[T]) Set(value T)
Set animates to a new target value. If called while an animation is in progress, the animation is retargeted: starts from current interpolated value and animates to new target.
func (*AnimatedValue[T]) SetImmediate ¶
func (av *AnimatedValue[T]) SetImmediate(value T)
SetImmediate sets the value without animation.
func (*AnimatedValue[T]) Signal ¶
func (av *AnimatedValue[T]) Signal() Signal[T]
Signal returns the underlying signal for advanced use cases.
func (*AnimatedValue[T]) Target ¶
func (av *AnimatedValue[T]) Target() T
Target returns the target value (where the animation is heading).
type AnimatedValueConfig ¶
type AnimatedValueConfig[T comparable] struct { Initial T Duration time.Duration Easing EasingFunc // Optional, defaults to EaseOutQuad Interpolator Interpolator[T] // Optional, uses registry if nil }
AnimatedValueConfig configures an AnimatedValue.
type Animation ¶
type Animation[T any] struct { // contains filtered or unexported fields }
Animation animates a value of type T over time. Create with NewAnimation and start with Start(). Read the current value with Value().Get() during Build() for reactive updates.
Start() can be called before the app is running. The animation will automatically begin when the animation controller becomes available.
Animation is not thread-safe; all methods must be called from the main goroutine.
func NewAnimation ¶
func NewAnimation[T any](config AnimationConfig[T]) *Animation[T]
NewAnimation creates a new animation with the given configuration. Panics if no interpolator is registered for type T and none is provided in config.
func (*Animation[T]) Advance ¶
Advance implements the Animator interface. Called by AnimationController on each tick.
func (*Animation[T]) Get ¶
func (a *Animation[T]) Get() T
Get returns the current value directly without subscribing.
func (*Animation[T]) IsComplete ¶
IsComplete returns true if the animation has finished.
func (*Animation[T]) Pause ¶
func (a *Animation[T]) Pause()
Pause temporarily suspends the animation.
func (*Animation[T]) Reset ¶
func (a *Animation[T]) Reset()
Reset restarts the animation from the beginning. Does not automatically start the animation; call Start() after Reset().
func (*Animation[T]) Start ¶
func (a *Animation[T]) Start()
Start begins the animation. The animation will register with the current AnimationController. If called before the app is running, the animation will automatically start when the controller becomes available (on first Value() access).
type AnimationConfig ¶
type AnimationConfig[T any] struct { From T To T Duration time.Duration Easing EasingFunc // Optional, defaults to EaseLinear Interpolator Interpolator[T] // Optional, uses registry if nil Delay time.Duration // Optional delay before animation starts OnComplete func() // Optional callback when animation completes OnUpdate func(T) // Optional callback on each value update }
AnimationConfig holds configuration for creating an Animation.
type AnimationController ¶
type AnimationController struct {
// contains filtered or unexported fields
}
AnimationController manages all active animations. It provides a tick channel that only sends when animations are active, implementing the "no animations = no ticker" optimization.
func NewAnimationController ¶
func NewAnimationController(fps int) *AnimationController
NewAnimationController creates a new controller with the given target FPS.
func (*AnimationController) HasActiveAnimations ¶
func (ac *AnimationController) HasActiveAnimations() bool
HasActiveAnimations returns true if any animations are running.
func (*AnimationController) Register ¶
func (ac *AnimationController) Register(anim Animator) *animationHandle
Register adds an animation to be managed by the controller. Returns a handle that can be used to unregister the animation.
func (*AnimationController) Stop ¶
func (ac *AnimationController) Stop()
Stop halts the controller and cleans up resources. Called when Run() exits.
func (*AnimationController) Tick ¶
func (ac *AnimationController) Tick() <-chan time.Time
Tick returns a channel that receives when animation updates are needed. Returns nil when no animations are active (nil channel blocks forever in select).
func (*AnimationController) Unregister ¶
func (ac *AnimationController) Unregister(handle *animationHandle)
Unregister removes an animation from the controller.
func (*AnimationController) Update ¶
func (ac *AnimationController) Update()
Update advances all animations and removes completed ones. Called from the event loop when Tick() receives.
type AnimationState ¶
type AnimationState int
AnimationState represents the current state of an animation.
const ( AnimationPending AnimationState = iota AnimationRunning AnimationPaused AnimationCompleted )
type Animator ¶
type Animator interface {
// Advance moves the animation forward by the given duration.
// Returns true if the animation is still running, false if complete.
Advance(dt time.Duration) bool
}
Animator is the interface for anything that can be animated.
type AnyAnimatedValue ¶
type AnyAnimatedValue[T any] struct { // contains filtered or unexported fields }
AnyAnimatedValue wraps a non-comparable value and animates transitions when Set() is called. Unlike AnimatedValue, this always animates on Set() since equality cannot be checked.
func NewAnyAnimatedValue ¶
func NewAnyAnimatedValue[T any](config AnyAnimatedValueConfig[T]) *AnyAnimatedValue[T]
NewAnyAnimatedValue creates a new animated value for non-comparable types. Panics if no interpolator is registered for type T and none is provided in config.
func (*AnyAnimatedValue[T]) Get ¶
func (av *AnyAnimatedValue[T]) Get() T
Get returns the current animated value. During Build(), this subscribes the widget to updates.
func (*AnyAnimatedValue[T]) IsAnimating ¶
func (av *AnyAnimatedValue[T]) IsAnimating() bool
IsAnimating returns true if an animation is in progress.
func (*AnyAnimatedValue[T]) Peek ¶
func (av *AnyAnimatedValue[T]) Peek() T
Peek returns the current value without subscribing.
func (*AnyAnimatedValue[T]) Set ¶
func (av *AnyAnimatedValue[T]) Set(value T)
Set animates to a new target value. Unlike AnimatedValue, this always starts a new animation since equality cannot be checked.
func (*AnyAnimatedValue[T]) SetImmediate ¶
func (av *AnyAnimatedValue[T]) SetImmediate(value T)
SetImmediate sets the value without animation.
func (*AnyAnimatedValue[T]) Signal ¶
func (av *AnyAnimatedValue[T]) Signal() AnySignal[T]
Signal returns the underlying signal for advanced use cases.
func (*AnyAnimatedValue[T]) Target ¶
func (av *AnyAnimatedValue[T]) Target() T
Target returns the target value (where the animation is heading).
type AnyAnimatedValueConfig ¶
type AnyAnimatedValueConfig[T any] struct { Initial T Duration time.Duration Easing EasingFunc // Optional, defaults to EaseOutQuad Interpolator Interpolator[T] // Optional, uses registry if nil }
AnyAnimatedValueConfig configures an AnyAnimatedValue.
type AnySignal ¶
type AnySignal[T any] struct { // contains filtered or unexported fields }
AnySignal holds reactive state for non-comparable types (like interfaces). Unlike Signal, it always notifies on Set() since equality cannot be checked. AnySignal can be stored by value in structs; copies share the same underlying state.
func NewAnySignal ¶
NewAnySignal creates a new signal for non-comparable types.
func (AnySignal[T]) Get ¶
func (s AnySignal[T]) Get() T
Get returns the current value. If called during a widget's Build(), the widget is automatically subscribed to future changes. Thread-safe: can be called from any goroutine.
func (AnySignal[T]) IsValid ¶
IsValid returns true if the signal was properly initialized. An uninitialized AnySignal (zero value) returns false.
func (AnySignal[T]) Peek ¶
func (s AnySignal[T]) Peek() T
Peek returns the current value without subscribing. Thread-safe: can be called from any goroutine.
type Autocomplete ¶
type Autocomplete struct {
ID string // Optional unique identifier
State *AutocompleteState // Required - holds popup and suggestion state
Child Widget // TextInput or TextArea
// Trigger behavior
TriggerChars []rune // e.g., {'@', '#'} - empty = always on
TriggerAtWordBoundary bool // Only trigger at word start (default: true)
MinChars int // Min chars after trigger to show popup (default 0)
// Selection & matching
MaxVisible int // Max visible items (default 8)
Insert InsertStrategy // Default: InsertFromTrigger if TriggerChars set, else InsertReplace
MatchMode FilterMode // FilterContains (default) or FilterFuzzy
// Dismissal behavior
DismissOnBlur *bool // Dismiss when input loses focus (default: true)
DismissWhenEmpty bool // Dismiss when no matches (default: false)
// If true, only attach popup keybinds when the popup is visible.
// This allows parent widgets to handle keys like Up/Down when hidden.
DisableKeysWhenHidden bool
// Callbacks
OnSelect func(Suggestion) // Called when a suggestion is selected
OnDismiss func() // Called when popup is dismissed
OnQueryChange func(string) // For async loading - called when query changes
// Dimensions
Width Dimension // Widget width
Height Dimension // Widget height
PopupWidth Dimension // Popup width (default: fit content)
AnchorToInput bool // Anchor popup to input content area and match its width
// Styling
Style Style // Widget styling
PopupStyle Style // Popup styling
// Custom rendering
RenderSuggestion func(Suggestion, bool, MatchResult, BuildContext) Widget
}
Autocomplete is a widget that wraps TextInput or TextArea to provide dropdown suggestions. The input keeps focus while navigating the popup.
func (Autocomplete) Build ¶
func (a Autocomplete) Build(ctx BuildContext) Widget
Build builds the autocomplete widget with popup overlay.
func (Autocomplete) GetContentDimensions ¶
func (a Autocomplete) GetContentDimensions() (width, height Dimension)
GetContentDimensions returns the width and height dimension preferences.
func (Autocomplete) WidgetID ¶
func (a Autocomplete) WidgetID() string
WidgetID returns the autocomplete's unique identifier.
type AutocompleteState ¶
type AutocompleteState struct {
Visible Signal[bool]
Suggestions AnySignal[[]Suggestion]
// contains filtered or unexported fields
}
AutocompleteState holds the state for an Autocomplete widget.
func NewAutocompleteState ¶
func NewAutocompleteState() *AutocompleteState
NewAutocompleteState creates a new AutocompleteState.
func (*AutocompleteState) IsVisible ¶
func (s *AutocompleteState) IsVisible() bool
IsVisible returns whether the popup is currently visible.
func (*AutocompleteState) SelectedSuggestion ¶
func (s *AutocompleteState) SelectedSuggestion() (Suggestion, bool)
SelectedSuggestion returns the currently selected suggestion, if any.
func (*AutocompleteState) SetSuggestions ¶
func (s *AutocompleteState) SetSuggestions(suggestions []Suggestion)
SetSuggestions sets the available suggestions.
type Blurrable ¶
type Blurrable interface {
OnBlur()
}
Blurrable is implemented by widgets that want to be notified when they lose keyboard focus. The framework calls OnBlur() when focus moves away from the widget.
type Border ¶
type Border struct {
Style BorderStyle
Color ColorProvider // Can be Color or Gradient
Decorations []BorderDecoration
}
Border defines the border appearance for a widget.
func AsciiBorder ¶
func AsciiBorder(color ColorProvider, decorations ...BorderDecoration) Border
AsciiBorder creates an ASCII-only border with the given color and optional decorations. Use this for maximum terminal compatibility.
+---+ | | +---+
func DashedBorder ¶
func DashedBorder(color ColorProvider, decorations ...BorderDecoration) Border
DashedBorder creates a dashed border with the given color and optional decorations.
func DoubleBorder ¶
func DoubleBorder(color ColorProvider, decorations ...BorderDecoration) Border
DoubleBorder creates a double-line border with the given color and optional decorations.
╔═══╗ ║ ║ ╚═══╝
func HeavyBorder ¶
func HeavyBorder(color ColorProvider, decorations ...BorderDecoration) Border
HeavyBorder creates a heavy/thick border with the given color and optional decorations.
┏━━━┓ ┃ ┃ ┗━━━┛
func RoundedBorder ¶
func RoundedBorder(color ColorProvider, decorations ...BorderDecoration) Border
RoundedBorder creates a rounded border with the given color and optional decorations.
╭───╮ │ │ ╰───╯
func SquareBorder ¶
func SquareBorder(color ColorProvider, decorations ...BorderDecoration) Border
SquareBorder creates a square border with the given color and optional decorations.
┌───┐ │ │ └───┘
type BorderCharSet ¶
type BorderCharSet struct {
TopLeft string
TopRight string
BottomLeft string
BottomRight string
Top string // Horizontal character for top edge
Bottom string // Horizontal character for bottom edge
Left string // Vertical character for left edge
Right string // Vertical character for right edge
}
BorderCharSet contains the characters used to render a border. Some border styles use different characters for each edge.
func GetBorderCharSet ¶
func GetBorderCharSet(style BorderStyle) BorderCharSet
GetBorderCharSet returns the character set for a given border style.
type BorderDecoration ¶
type BorderDecoration struct {
Text string // Plain text (used if Markup is empty)
Markup string // Markup string, parsed at render time for styled text
Position DecorationPosition
Color ColorProvider // Fallback color if markup has no color (or for plain text)
}
BorderDecoration defines a text label on a border edge.
func BorderSubtitle ¶
func BorderSubtitle(text string) BorderDecoration
BorderSubtitle creates a subtitle decoration at the bottom-left of the border.
func BorderSubtitleCenter ¶
func BorderSubtitleCenter(text string) BorderDecoration
BorderSubtitleCenter creates a subtitle decoration at the bottom-center of the border.
func BorderSubtitleCenterMarkup ¶
func BorderSubtitleCenterMarkup(markup string) BorderDecoration
BorderSubtitleCenterMarkup creates a subtitle decoration with markup at the bottom-center of the border.
func BorderSubtitleMarkup ¶
func BorderSubtitleMarkup(markup string) BorderDecoration
BorderSubtitleMarkup creates a subtitle decoration with markup at the bottom-left of the border.
func BorderSubtitleRight ¶
func BorderSubtitleRight(text string) BorderDecoration
BorderSubtitleRight creates a subtitle decoration at the bottom-right of the border.
func BorderSubtitleRightMarkup ¶
func BorderSubtitleRightMarkup(markup string) BorderDecoration
BorderSubtitleRightMarkup creates a subtitle decoration with markup at the bottom-right of the border.
func BorderTitle ¶
func BorderTitle(text string) BorderDecoration
BorderTitle creates a title decoration at the top-left of the border.
func BorderTitleCenter ¶
func BorderTitleCenter(text string) BorderDecoration
BorderTitleCenter creates a title decoration at the top-center of the border.
func BorderTitleCenterMarkup ¶
func BorderTitleCenterMarkup(markup string) BorderDecoration
BorderTitleCenterMarkup creates a title decoration with markup at the top-center of the border.
func BorderTitleMarkup ¶
func BorderTitleMarkup(markup string) BorderDecoration
BorderTitleMarkup creates a title decoration with markup at the top-left of the border. The markup is parsed at render time to access the theme.
func BorderTitleRight ¶
func BorderTitleRight(text string) BorderDecoration
BorderTitleRight creates a title decoration at the top-right of the border.
func BorderTitleRightMarkup ¶
func BorderTitleRightMarkup(markup string) BorderDecoration
BorderTitleRightMarkup creates a title decoration with markup at the top-right of the border.
type BorderStyle ¶
type BorderStyle int
BorderStyle defines the visual style of a border.
const ( BorderNone BorderStyle = iota BorderSquare BorderRounded BorderDouble BorderHeavy BorderDashed BorderAscii )
Border style constants.
type Breadcrumbs ¶
type Breadcrumbs struct {
ID string
Path []string
OnSelect func(index int) // Click to navigate
Separator string // Default: ">"
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style
}
Breadcrumbs renders a clickable breadcrumb path.
func (Breadcrumbs) Build ¶
func (b Breadcrumbs) Build(ctx BuildContext) Widget
Build renders the breadcrumb path as a row of text segments.
type BuildContext ¶
type BuildContext struct {
// contains filtered or unexported fields
}
BuildContext provides access to framework state during widget building. It is passed to Widget.Build() to allow widgets to access focus state, hover state, and other framework features in a declarative way.
func NewBuildContext ¶
func NewBuildContext(fm *FocusManager, focusedSignal AnySignal[Focusable], hoveredSignal AnySignal[Widget], fc *FloatCollector) BuildContext
NewBuildContext creates a new build context.
func (BuildContext) ActiveKeybinds ¶
func (ctx BuildContext) ActiveKeybinds() []Keybind
ActiveKeybinds returns all declarative keybindings currently active based on the focused widget and its ancestors. Useful for displaying available keybindings in a footer or help screen.
func (BuildContext) AutoID ¶
func (ctx BuildContext) AutoID() string
AutoID returns an automatically generated ID based on tree position. This is used for state persistence when widgets don't provide an explicit ID.
func (BuildContext) Focused ¶
func (ctx BuildContext) Focused() Focusable
Focused returns the currently focused widget, or nil if none. This is a reactive value - reading it during Build() will cause the widget to rebuild when focus changes.
func (BuildContext) FocusedSignal ¶
func (ctx BuildContext) FocusedSignal() AnySignal[Focusable]
FocusedSignal returns the signal holding the focused widget. Useful for more advanced reactive patterns.
func (BuildContext) Hovered ¶
func (ctx BuildContext) Hovered() Widget
Hovered returns the currently hovered widget, or nil if none. This is a reactive value - reading it during Build() will cause the widget to rebuild when hover changes.
func (BuildContext) HoveredID ¶
func (ctx BuildContext) HoveredID() string
HoveredID returns the ID of the currently hovered widget ("" if none). This is a reactive value - reading it during Build() will cause the widget to rebuild when hover changes.
func (BuildContext) IsDisabled ¶
func (ctx BuildContext) IsDisabled() bool
IsDisabled returns true if within a disabled subtree. Widgets can check this to render in a disabled state and skip interactive behavior.
func (BuildContext) IsFocused ¶
func (ctx BuildContext) IsFocused(widget Widget) bool
IsFocused returns true if the given widget currently has focus. Widgets with an explicit ID are matched by that ID; otherwise the position-based AutoID is used as a fallback.
func (BuildContext) IsHovered ¶
func (ctx BuildContext) IsHovered(widget Widget) bool
IsHovered returns true if the given widget is currently being hovered. The widget must implement Identifiable for hover comparison.
func (BuildContext) PushChild ¶
func (ctx BuildContext) PushChild(index int) BuildContext
PushChild creates a child context with the given index appended to the path. Used by container widgets when rendering children.
func (BuildContext) RequestFocus ¶
func (ctx BuildContext) RequestFocus(id string)
RequestFocus requests that the widget with the given ID receive focus after the current render cycle completes. This is useful for programmatically moving focus, such as when showing inline edit fields.
Example:
func (a *App) startEdit() {
a.editingIndex.Set(currentIndex)
// Focus will be applied after the next render
}
func (a *App) Build(ctx BuildContext) Widget {
if a.editingIndex.Get() >= 0 {
ctx.RequestFocus("edit-input")
}
// ...
}
func (BuildContext) Theme ¶
func (ctx BuildContext) Theme() ThemeData
Theme returns the current theme data. This is a reactive value - reading it during Build() will cause the widget to rebuild when the theme changes.
Example:
func (w *MyWidget) Build(ctx BuildContext) Widget {
theme := ctx.Theme()
return Text{
Content: "Hello",
Style: Style{
ForegroundColor: theme.Text,
BackgroundColor: theme.Surface,
},
}
}
func (BuildContext) WithDisabled ¶
func (ctx BuildContext) WithDisabled() BuildContext
WithDisabled returns a copy of the context with disabled=true. Used by DisabledWhen wrapper to mark a subtree as disabled.
type Button ¶
type Button struct {
ID string // Optional unique identifier for the button
DisableFocus bool // If true, prevent keyboard focus
Label string // Display text for the button
Variant ButtonVariant // Semantic color variant (default: ButtonDefault)
OnPress func() // Callback invoked when button is pressed
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling (colors) applied when not focused
Click func(MouseEvent) // Optional callback invoked when clicked
MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed
MouseUp func(MouseEvent) // Optional callback invoked when mouse is released
Hover func(HoverEvent) // Optional callback invoked when hover state changes
}
Button is a focusable widget that renders as styled text. It can be pressed with Enter or Space when focused.
func (Button) Build ¶
func (b Button) Build(ctx BuildContext) Widget
Build returns a Text widget with appropriate styling based on focus state. Buttons are rendered with bracket affordance: [label] When focused, the button is highlighted with variant colors (or theme.Primary for default). When disabled, the button shows disabled styling and brackets are faded. If no explicit style colors are set, variant-derived defaults are applied.
func (Button) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences. Implements the Dimensioned interface.
func (Button) IsFocusable ¶
IsFocusable returns true, indicating this button can receive keyboard focus. Implements the Focusable interface.
func (Button) Keybinds ¶
Keybinds returns the declarative keybindings for this button. The button responds to Enter and Space to trigger the OnPress callback. Implements the KeybindProvider interface.
func (Button) OnClick ¶
func (b Button) OnClick(event MouseEvent)
OnClick is called when the widget is clicked. Implements the Clickable interface.
func (Button) OnHover ¶
func (b Button) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions. Implements the Hoverable interface.
func (Button) OnKey ¶
OnKey handles keys not covered by declarative keybindings. Since Enter and Space are handled via Keybinds(), this returns false. Implements the Focusable interface.
func (Button) OnMouseDown ¶
func (b Button) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (Button) OnMouseUp ¶
func (b Button) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
type ButtonVariant ¶
type ButtonVariant int
ButtonVariant represents the semantic color variant for a Button.
const ( ButtonDefault ButtonVariant = iota ButtonPrimary ButtonAccent ButtonSuccess ButtonError ButtonWarning ButtonInfo )
type CellBuffer ¶
CellBuffer is the interface for cell-based rendering. Both *uv.Terminal and *uv.Buffer satisfy this interface.
type Checkbox ¶
type Checkbox struct {
ID string // Optional unique identifier for the checkbox
DisableFocus bool // If true, prevent keyboard focus
State *CheckboxState // Required - holds checked state
Label string // Optional text displayed after the indicator
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling applied when not focused
OnChange func(bool) // Optional callback invoked after state changes
Click func(MouseEvent) // Optional callback invoked when clicked
MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed
MouseUp func(MouseEvent) // Optional callback invoked when mouse is released
Hover func(HoverEvent) // Optional callback invoked when hover state changes
}
Checkbox is a focusable widget that displays a checkable box with an optional label. It can be toggled with Enter or Space when focused.
func (*Checkbox) Build ¶
func (c *Checkbox) Build(ctx BuildContext) Widget
Build returns a Text widget with the checkbox indicator and label. The checkbox is rendered with appropriate styling based on focus and disabled state.
func (*Checkbox) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences. Implements the Dimensioned interface.
func (*Checkbox) IsFocusable ¶
IsFocusable returns true, indicating this checkbox can receive keyboard focus. Implements the Focusable interface.
func (*Checkbox) Keybinds ¶
Keybinds returns the declarative keybindings for this checkbox. The checkbox responds to Enter and Space to toggle the checked state. Implements the KeybindProvider interface.
func (*Checkbox) OnClick ¶
func (c *Checkbox) OnClick(event MouseEvent)
OnClick is called when the widget is clicked. It toggles the checkbox state and invokes the Click callback. Implements the Clickable interface.
func (*Checkbox) OnHover ¶
func (c *Checkbox) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions. Implements the Hoverable interface.
func (*Checkbox) OnKey ¶
OnKey handles keys not covered by declarative keybindings. Since Enter and Space are handled via Keybinds(), this returns false. Implements the Focusable interface.
func (*Checkbox) OnMouseDown ¶
func (c *Checkbox) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (*Checkbox) OnMouseUp ¶
func (c *Checkbox) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
type CheckboxState ¶
CheckboxState holds the state for a Checkbox widget. It is the source of truth for the checked state and must be provided to Checkbox.
func NewCheckboxState ¶
func NewCheckboxState(checked bool) *CheckboxState
NewCheckboxState creates a new CheckboxState with the given initial checked value.
func (*CheckboxState) IsChecked ¶
func (s *CheckboxState) IsChecked() bool
IsChecked returns the current checked state without subscribing to changes.
func (*CheckboxState) SetChecked ¶
func (s *CheckboxState) SetChecked(checked bool)
SetChecked sets the checked state to the given value.
type ChildProvider ¶
type ChildProvider interface {
ChildWidgets() []Widget
}
ChildProvider exposes a widget's children for render tree construction. Implement this for custom containers so computed child layouts are rendered.
type Clickable ¶
type Clickable interface {
OnClick(event MouseEvent)
}
Clickable is implemented by widgets that respond to mouse clicks.
type Color ¶
type Color struct {
// contains filtered or unexported fields
}
Color represents a terminal color with full RGB, HSL, and alpha support. The zero value (Color{}) is transparent/default - inherits from terminal. Alpha values < 1.0 enable transparency:
- For background colors: blends with inherited background
- For foreground colors: blends with effective background, creating faded text
Color implements ColorProvider by returning itself at any position.
func FromANSI ¶
FromANSI converts an ANSI color (from terminal cells) back to our Color type. Returns an unset Color if the input is nil.
func HSL ¶
HSL creates a color from hue (0-360), saturation (0-1), lightness (0-1). The resulting color is fully opaque (alpha = 1.0).
func HSLA ¶
HSLA creates a color from hue (0-360), saturation (0-1), lightness (0-1), and alpha (0-1).
func Hex ¶
Hex creates a color from a hex string. Accepts formats: "#RRGGBB", "RRGGBB", "#RGB", "RGB", "#RRGGBBAA", "RRGGBBAA". For 8-character format, AA is the alpha value (00 = transparent, FF = opaque).
func RGB ¶
RGB creates a color from red, green, blue components (0-255). The resulting color is fully opaque (alpha = 1.0).
func RGBA ¶
RGBA creates a color from red, green, blue components (0-255) and alpha (0.0-1.0). Alpha of 0.0 is fully transparent, 1.0 is fully opaque.
func (Color) AutoText ¶
AutoText returns a text color that is readable against this background color. It blends the background with white (for dark backgrounds) or black (for light backgrounds), preserving some of the background's character while ensuring WCAG AA compliant contrast (≥4.5:1).
func (Color) Blend ¶
Blend mixes this color with another color. ratio of 0 returns this color, ratio of 1 returns the other color.
func (Color) BlendOver ¶
BlendOver composites this color over a background color using alpha blending. This is the standard "over" operator for alpha compositing. Returns a fully opaque color representing the visual result.
func (Color) ColorAt ¶
ColorAt returns the color unchanged (solid colors are constant across the region). This implements ColorProvider.
func (Color) Complement ¶
Complement returns the complementary color (hue rotated 180 degrees).
func (Color) ContrastRatio ¶
ContrastRatio returns the WCAG contrast ratio between two colors. The ratio ranges from 1:1 (identical) to 21:1 (black on white).
func (Color) Darken ¶
Darken decreases the lightness of the color proportionally. amount should be between 0 and 1, representing the percentage to reduce lightness. For example, Darken(0.1) reduces lightness by 10% of its current value.
func (Color) Desaturate ¶
Desaturate decreases the saturation of the color. amount should be between 0 and 1.
func (Color) Lighten ¶
Lighten increases the lightness of the color proportionally. amount should be between 0 and 1. This is the inverse of Darken, so color.Darken(x).Lighten(x) returns approximately the original color.
func (Color) Luminance ¶
Luminance returns the relative luminance of the color (0-1). Uses the WCAG formula for calculating relative luminance.
type ColorProvider ¶
type ColorProvider interface {
// ColorAt returns the color at position (x, y) within a region of given width and height.
ColorAt(width, height, x, y int) Color
// IsSet returns true if this provider was explicitly set.
IsSet() bool
}
ColorProvider can provide a color at any position within a region. Implemented by Color (returns constant) and Gradient (interpolates by position).
type Column ¶
type Column struct {
ID string // Optional unique identifier for the widget
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling (background color)
Spacing int // Space between children
MainAlign MainAxisAlign // Main axis (vertical) alignment
CrossAlign CrossAxisAlign // Cross axis (horizontal) alignment
Children []Widget
Click func(MouseEvent) // Optional callback invoked when clicked
MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed
MouseUp func(MouseEvent) // Optional callback invoked when mouse is released
Hover func(HoverEvent) // Optional callback invoked when hover state changes
}
Column arranges its children vertically.
func (Column) Build ¶
func (c Column) Build(ctx BuildContext) Widget
Build returns itself as Column manages its own children.
func (Column) BuildLayoutNode ¶
func (c Column) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode creates a ColumnNode for the layout system.
func (Column) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences.
func (Column) OnClick ¶
func (c Column) OnClick(event MouseEvent)
OnClick is called when the widget is clicked. Implements the Clickable interface.
func (Column) OnHover ¶
func (c Column) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions. Implements the Hoverable interface.
func (Column) OnMouseDown ¶
func (c Column) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (Column) OnMouseUp ¶
func (c Column) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
func (Column) Render ¶
func (c Column) Render(ctx *RenderContext)
Render is a no-op for Column when using the RenderTree-based rendering path.
type CommandPalette ¶
type CommandPalette struct {
ID string
State *CommandPaletteState
OnSelect func(item CommandPaletteItem) // Custom selection handler
OnCursorChange func(item CommandPaletteItem) // For live previews
OnDismiss func()
RenderItem func(item CommandPaletteItem, active bool, match MatchResult) Widget
DisableBackspaceToPop bool // If true, backspace only edits the input (no auto-pop to previous level)
Width Dimension // Deprecated: use Style.Width (default: Cells(60))
Height Dimension // Deprecated: use Style.Height (default: Cells(12))
Placeholder string // Default: "Type to search..."
Position FloatPosition
Offset Offset
BackdropColor Color // Optional modal backdrop color override (default: theme.Overlay)
Style Style
}
CommandPalette renders a searchable command palette with nested navigation.
func (CommandPalette) Build ¶
func (p CommandPalette) Build(ctx BuildContext) Widget
Build renders the command palette as a floating modal.
type CommandPaletteItem ¶
type CommandPaletteItem struct {
Label string // Primary display text
Hint string // Right-aligned text (e.g., "Ctrl+N")
HintWidget func() Widget // Custom hint widget (color swatches, etc.)
Description string // Optional secondary line below label
Action func() // Called on selection (ignored if Children set)
Children func() []CommandPaletteItem // Opens nested palette (lazy-loaded)
ChildrenTitle string // Breadcrumb title for nested level
Disabled bool // Grayed out, not selectable
Divider string // Empty = plain line, non-empty = titled
FilterText string // Override Label for filtering
Data any // User data for custom renderers
}
CommandPaletteItem represents a single entry in the command palette.
func (CommandPaletteItem) GetFilterText ¶
func (i CommandPaletteItem) GetFilterText() string
GetFilterText returns the text used for filtering.
func (CommandPaletteItem) IsDivider ¶
func (i CommandPaletteItem) IsDivider() bool
IsDivider returns true if this item should render as a divider.
func (CommandPaletteItem) IsSelectable ¶
func (i CommandPaletteItem) IsSelectable() bool
IsSelectable returns true if the item can be focused/selected.
type CommandPaletteLevel ¶
type CommandPaletteLevel struct {
Title string
Items []CommandPaletteItem
ListState *ListState[CommandPaletteItem]
ScrollState *ScrollState
FilterState *FilterState
InputState *TextInputState
}
CommandPaletteLevel holds the state for a single palette level.
type CommandPaletteState ¶
CommandPaletteState holds the stack of palette levels and visibility state.
func NewCommandPaletteState ¶
func NewCommandPaletteState(title string, items []CommandPaletteItem) *CommandPaletteState
NewCommandPaletteState creates a new palette state with a root level.
func (*CommandPaletteState) BreadcrumbPath ¶
func (s *CommandPaletteState) BreadcrumbPath() []string
BreadcrumbPath returns the current breadcrumb trail.
func (*CommandPaletteState) Close ¶
func (s *CommandPaletteState) Close(keepPosition bool)
Close hides the command palette. If keepPosition is false, the palette resets to the root level for the next open.
func (*CommandPaletteState) CurrentItem ¶
func (s *CommandPaletteState) CurrentItem() (CommandPaletteItem, bool)
CurrentItem returns the currently selected item (if any).
func (*CommandPaletteState) CurrentLevel ¶
func (s *CommandPaletteState) CurrentLevel() *CommandPaletteLevel
CurrentLevel returns the active level.
func (*CommandPaletteState) IsNested ¶
func (s *CommandPaletteState) IsNested() bool
IsNested returns true if there is more than one level.
func (*CommandPaletteState) Open ¶
func (s *CommandPaletteState) Open()
Open shows the command palette.
func (*CommandPaletteState) PopLevel ¶
func (s *CommandPaletteState) PopLevel() bool
PopLevel removes the current level, returning true if a level was popped.
func (*CommandPaletteState) PushLevel ¶
func (s *CommandPaletteState) PushLevel(title string, items []CommandPaletteItem)
PushLevel adds a new level to the stack.
func (*CommandPaletteState) SetItems ¶
func (s *CommandPaletteState) SetItems(items []CommandPaletteItem)
SetItems replaces the items in the current level.
func (*CommandPaletteState) SetNextFocusIDOnClose ¶
func (s *CommandPaletteState) SetNextFocusIDOnClose(id string)
SetNextFocusIDOnClose overrides the focus target used on the next close. If empty, normal focus restore behavior is used.
type Constraints ¶
Constraints define the min/max dimensions a widget can occupy.
type CrossAxisAlign ¶
type CrossAxisAlign int
CrossAxisAlign specifies how children are aligned along the cross axis. For Row, cross axis is vertical. For Column, cross axis is horizontal.
const ( // CrossAxisStart aligns children at the start of the cross axis. CrossAxisStart CrossAxisAlign = iota // CrossAxisStretch stretches children to fill the cross axis (default). CrossAxisStretch // CrossAxisCenter centers children along the cross axis. CrossAxisCenter // CrossAxisEnd aligns children at the end of the cross axis. CrossAxisEnd )
type CursorStyle ¶
type CursorStyle struct {
CursorPrefix string // Prefix shown on active/cursor item (default: "")
SelectedPrefix string // Prefix shown on selected items in multi-select (default: "")
}
CursorStyle configures the visual appearance of cursor and selection in list-like widgets. Embed this anonymously in widgets to get CursorPrefix/SelectedPrefix fields.
By default, no prefixes are shown - the cursor and selection are indicated via background color highlighting only. Users who prefer or need visual indicators (e.g., for accessibility) can set CursorPrefix to "▶ " or similar.
Example:
List[string]{
CursorPrefix: "▶ ", // Show arrow on cursor row
SelectedPrefix: "* ", // Show asterisk on selected rows
State: myState,
}
type DecorationPosition ¶
type DecorationPosition int
DecorationPosition defines where a decoration appears on the border.
const ( DecorationTopLeft DecorationPosition = iota DecorationTopCenter DecorationTopRight DecorationBottomLeft DecorationBottomCenter DecorationBottomRight )
Decoration position constants.
type Dialog ¶
type Dialog struct {
ID string // Optional stable ID for focus management and button IDs
Visible bool // Controls visibility
Title string // Shown in border title (optional)
Content Widget // Body content
Buttons []Button // Action buttons, rendered left-to-right
OnDismiss func() // Called on Escape / click outside (optional)
Style Style // Override default styling
}
Dialog is a convenience widget that wraps Floating + layout to create a modal dialog with a title, content, and action buttons.
When Visible is true, the dialog is rendered as a centered modal overlay with a backdrop. Focus is automatically trapped within the dialog. The first button receives focus when the dialog becomes visible.
Example:
Dialog{
ID: "confirm-dialog",
Visible: a.showDialog.Get(),
Title: "Confirm Delete",
Content: Text{Content: "Are you sure?"},
Buttons: []Button{
{Label: "Cancel", OnPress: func() { a.showDialog.Set(false) }},
{Label: "Delete", Variant: ButtonError, OnPress: a.delete},
},
OnDismiss: func() { a.showDialog.Set(false) },
}
func (Dialog) Build ¶
func (d Dialog) Build(ctx BuildContext) Widget
Build registers the dialog with the float collector (when visible) and returns EmptyWidget. Like Floating, the dialog content is rendered as an overlay after the main widget tree.
type Dimension ¶
type Dimension struct {
// contains filtered or unexported fields
}
Dimension represents a size specification for widgets. The zero value represents auto-sizing (fit content).
func Flex ¶
Flex returns a flexible dimension for proportional space distribution. Children with Flex dimensions share remaining space proportionally. For example, Flex(1) and Flex(2) siblings get 1/3 and 2/3 of remaining space.
func Percent ¶
Percent returns a dimension as a percentage of the parent's available space. For example, Percent(50) means 50% of the parent's width or height. Unlike Flex, percentages are calculated from the total available space, not from the remaining space after fixed children.
func (Dimension) CellsValue ¶
CellsValue returns the fixed cell count (only valid if IsCells() is true).
func (Dimension) IsUnset ¶
IsUnset returns true if this dimension was not explicitly set (zero value).
func (Dimension) PercentValue ¶
PercentValue returns the percentage value (only valid if IsPercent() is true).
type DimensionSet ¶
type DimensionSet struct {
Width, Height Dimension
MinWidth, MinHeight Dimension
MaxWidth, MaxHeight Dimension
}
DimensionSet groups size preferences and constraints for a widget. Width/Height describe the preferred content-box size. Min/Max fields constrain the content-box size range.
func GetWidgetDimensionSet ¶
func GetWidgetDimensionSet(widget Widget) DimensionSet
GetWidgetDimensionSet returns resolved dimensions for a widget. Style dimensions override Dimensioned dimensions when explicitly set.
func (DimensionSet) WithDefaults ¶
func (d DimensionSet) WithDefaults(width, height Dimension) DimensionSet
WithDefaults applies default width/height if unset.
type Dimensioned ¶
type Dimensioned interface {
GetContentDimensions() (width, height Dimension)
}
Dimensioned is implemented by widgets that have explicit dimension preferences. This allows parent containers to query child dimensions for fractional layout.
GetContentDimensions returns the content-box dimensions - the space needed for the widget's content, NOT including padding or border. The framework automatically adds padding and border from the widget's Style to compute the final outer size.
For example, a TextInput might return Cells(1) for height (one line of text content), and if it has Style{Padding: EdgeInsetsXY(1,1)}, the final height will be 3 cells.
type DirectoryEntry ¶
DirectoryEntry represents a filesystem entry used by DirectoryTree.
type DirectoryTree ¶
type DirectoryTree struct {
Tree[DirectoryEntry]
// ReadDir returns the direct children of path. Default uses os.ReadDir.
ReadDir func(path string) ([]DirectoryEntry, error)
// EagerLoad preloads all directory children (recursively) in the background.
// Loaded nodes remain collapsed until expanded.
EagerLoad bool
// IncludeHidden controls whether entries starting with "." are included.
IncludeHidden bool
// Sort controls entry ordering; default sorts directories first by name.
Sort func([]DirectoryEntry)
}
DirectoryTree is a utility widget that renders a filesystem tree using Tree.
func (DirectoryTree) Build ¶
func (d DirectoryTree) Build(ctx BuildContext) Widget
Build renders a Tree[DirectoryEntry] with filesystem-aware defaults.
func (DirectoryTree) IsFocusable ¶
func (d DirectoryTree) IsFocusable() bool
IsFocusable returns true to allow keyboard navigation.
func (DirectoryTree) Keybinds ¶
func (d DirectoryTree) Keybinds() []Keybind
Keybinds returns the declarative keybindings for this directory tree.
func (DirectoryTree) OnKey ¶
func (d DirectoryTree) OnKey(event KeyEvent) bool
OnKey handles keys not covered by declarative keybindings.
func (DirectoryTree) WidgetID ¶
func (d DirectoryTree) WidgetID() string
WidgetID returns the directory tree's unique identifier.
type Dock ¶
type Dock struct {
ID string // Optional unique identifier
Top []Widget // Widgets docked to top edge
Bottom []Widget // Widgets docked to bottom edge
Left []Widget // Widgets docked to left edge
Right []Widget // Widgets docked to right edge
Body Widget // Widget that fills remaining space
DockOrder []Edge // Order in which edges are processed (default: Top, Bottom, Left, Right)
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling
}
Dock arranges children by docking them to edges. Works like WPF DockPanel: edges consume space in order, body fills remainder.
Example:
Dock{
Top: []Widget{Header{}},
Bottom: []Widget{KeybindBar{}},
Left: []Widget{Sidebar{}},
Body: MainContent{},
}
func (Dock) AllChildren ¶
AllChildren returns all children in layout order (for extractChildren). The order matches how BuildLayoutNode processes edges plus body.
func (Dock) Build ¶
func (d Dock) Build(ctx BuildContext) Widget
Build returns self (Dock manages its own children).
func (Dock) BuildLayoutNode ¶
func (d Dock) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode creates a DockNode for the layout system.
func (Dock) GetContentDimensions ¶
GetContentDimensions returns dimensions (defaults to Flex(1) for both).
func (Dock) Render ¶
func (d Dock) Render(ctx *RenderContext)
Render is a no-op (children positioned by renderTree).
type EasingFunc ¶
EasingFunc defines the easing curve for an animation. Takes t in range [0, 1] and returns the eased value in range [0, 1].
type Edge ¶
Edge specifies which edge a child is docked to. This is a re-export of layout.DockEdge for widget API.
type EdgeInsets ¶
type EdgeInsets struct {
Top, Right, Bottom, Left int
}
EdgeInsets represents spacing around the four edges of a widget.
func EdgeInsetsAll ¶
func EdgeInsetsAll(value int) EdgeInsets
EdgeInsetsAll creates EdgeInsets with the same value for all sides.
func EdgeInsetsTRBL ¶
func EdgeInsetsTRBL(top, right, bottom, left int) EdgeInsets
EdgeInsetsTRBL creates EdgeInsets with individual values for each side.
func EdgeInsetsXY ¶
func EdgeInsetsXY(horizontal, vertical int) EdgeInsets
EdgeInsetsXY creates EdgeInsets with separate horizontal and vertical values.
func (EdgeInsets) Horizontal ¶
func (e EdgeInsets) Horizontal() int
Horizontal returns the total horizontal inset (Left + Right).
func (EdgeInsets) Vertical ¶
func (e EdgeInsets) Vertical() int
Vertical returns the total vertical inset (Top + Bottom).
type EmptyWidget ¶
type EmptyWidget struct{}
EmptyWidget is a placeholder widget that renders nothing and takes no space. Use this directly or via ShowWhen/HideWhen for conditional rendering.
func (EmptyWidget) Build ¶
func (e EmptyWidget) Build(ctx BuildContext) Widget
Build returns itself since EmptyWidget handles its own layout and rendering.
func (EmptyWidget) Layout ¶
func (e EmptyWidget) Layout(_ BuildContext, _ Constraints) Size
Layout returns zero size - EmptyWidget takes no space in the layout.
func (EmptyWidget) Render ¶
func (e EmptyWidget) Render(_ *RenderContext)
Render does nothing - EmptyWidget is invisible.
type FilterMode ¶
type FilterMode int
FilterMode controls how text matching is performed.
const ( // FilterContains matches contiguous substrings (default). FilterContains FilterMode = iota // FilterFuzzy matches characters in order (subsequence); ranked consumers // prefer matches near the start of the string. FilterFuzzy )
type FilterOptions ¶
type FilterOptions struct {
Mode FilterMode
CaseSensitive bool
}
FilterOptions configures text matching behavior.
type FilterState ¶
FilterState holds reactive filter input and matching options.
func NewFilterState ¶
func NewFilterState() *FilterState
NewFilterState creates a FilterState with default options.
func (*FilterState) Options ¶
func (s *FilterState) Options() FilterOptions
Options returns the current filter options (subscribes to changes).
func (*FilterState) PeekOptions ¶
func (s *FilterState) PeekOptions() FilterOptions
PeekOptions returns the current filter options without subscribing.
func (*FilterState) PeekQuery ¶
func (s *FilterState) PeekQuery() string
PeekQuery returns the current query text without subscribing.
func (*FilterState) QueryText ¶
func (s *FilterState) QueryText() string
QueryText returns the current query text (subscribes to changes).
type FilteredView ¶
type FilteredView[T any] struct { Items []T Indices []int Matches []MatchResult }
FilteredView contains the filtered slice, source indices, and match data.
func ApplyFilter ¶
func ApplyFilter[T any](items []T, query string, match func(item T, query string) MatchResult) FilteredView[T]
ApplyFilter filters items using the matcher and returns the view with match data.
type FloatCollector ¶
type FloatCollector struct {
// contains filtered or unexported fields
}
FloatCollector gathers Floating widgets during the build phase for rendering after the main widget tree.
func NewFloatCollector ¶
func NewFloatCollector() *FloatCollector
NewFloatCollector creates a new float collector.
func (*FloatCollector) Add ¶
func (c *FloatCollector) Add(entry FloatEntry)
Add registers a floating widget entry.
func (*FloatCollector) Entries ¶
func (c *FloatCollector) Entries() []FloatEntry
Entries returns all registered floating widgets.
func (*FloatCollector) HasModal ¶
func (c *FloatCollector) HasModal() bool
HasModal returns true if any registered float is modal.
func (*FloatCollector) Len ¶
func (c *FloatCollector) Len() int
Len returns the number of registered floats.
func (*FloatCollector) Reset ¶
func (c *FloatCollector) Reset()
Reset clears all entries for a new render pass.
func (*FloatCollector) TopModal ¶
func (c *FloatCollector) TopModal() *FloatEntry
TopModal returns the topmost modal float entry, or nil if none.
type FloatConfig ¶
type FloatConfig struct {
// Anchor-based positioning (use AnchorID + Anchor).
// If AnchorID is set, the float is positioned relative to that widget.
AnchorID string // ID of the widget to anchor to
Anchor AnchorPoint // Where on the anchor widget to attach
// Absolute positioning (used when AnchorID is empty).
Position FloatPosition
// Offset from the calculated position.
Offset Offset
// Modal behavior - when true, traps focus and shows a backdrop.
Modal bool
// DismissOnEsc dismisses the float when Escape is pressed.
// Defaults to true if OnDismiss is set.
DismissOnEsc *bool
// DismissOnClickOutside dismisses the float when clicking outside it.
// Defaults to true for non-modal floats when OnDismiss is set.
DismissOnClickOutside *bool
// OnDismiss is called when the float should be dismissed.
OnDismiss func()
// BackdropColor is the color of the modal backdrop.
// Only used when Modal is true. Defaults to semi-transparent black.
BackdropColor Color
}
FloatConfig configures positioning and behavior for a floating widget.
type FloatEntry ¶
type FloatEntry struct {
Config FloatConfig
Child Widget
// Computed position after layout (set during render phase)
X, Y int
Width, Height int
}
FloatEntry stores a registered floating widget for deferred rendering.
type FloatPosition ¶
type FloatPosition int
FloatPosition specifies absolute positioning for floating widgets.
const ( // FloatPositionAbsolute uses the Offset as absolute screen coordinates. FloatPositionAbsolute FloatPosition = iota // FloatPositionCenter centers the float on the screen. FloatPositionCenter // FloatPositionTopLeft positions the float at the top left of the screen. FloatPositionTopLeft // FloatPositionTopCenter positions the float at the top center of the screen. FloatPositionTopCenter // FloatPositionTopRight positions the float at the top right of the screen. FloatPositionTopRight // FloatPositionBottomLeft positions the float at the bottom left of the screen. FloatPositionBottomLeft // FloatPositionBottomCenter positions the float at the bottom center of the screen. FloatPositionBottomCenter // FloatPositionBottomRight positions the float at the bottom right of the screen. FloatPositionBottomRight )
type Floating ¶
type Floating struct {
// Visible controls whether the floating widget is shown.
Visible bool
// Config specifies positioning and behavior.
Config FloatConfig
// Child is the widget to render as an overlay.
Child Widget
}
Floating is a widget that renders its child as an overlay on top of other widgets. The child is rendered after the main widget tree, ensuring it appears on top.
For modal floats (Modal: true), the backdrop blocks clicks to underlying widgets, Escape dismisses the modal, and focus is trapped within the modal's subtree via FocusTrap — Tab/Shift+Tab will only cycle through focusable widgets inside the modal. Use RequestFocus to move focus into the modal when opening it.
Example - dropdown menu anchored to a button:
Floating{
Visible: m.showMenu.Get(),
Config: FloatConfig{
AnchorID: "file-btn",
Anchor: AnchorBottomLeft,
OnDismiss: func() { m.showMenu.Set(false) },
},
Child: Menu{Items: menuItems},
}
Example - centered modal dialog:
Floating{
Visible: a.showDialog.Get(),
Config: FloatConfig{
Position: FloatPositionCenter,
Modal: true,
OnDismiss: func() { a.showDialog.Set(false) },
},
Child: Dialog{Title: "Confirm", ...},
}
func (Floating) Build ¶
func (f Floating) Build(ctx BuildContext) Widget
Build registers the floating widget with the collector if visible. Returns an empty widget since the actual rendering happens in the overlay phase.
type FocusCollector ¶
type FocusCollector struct {
// contains filtered or unexported fields
}
FocusCollector collects focusable widgets during render traversal.
func NewFocusCollector ¶
func NewFocusCollector() *FocusCollector
NewFocusCollector creates a new focus collector.
func (*FocusCollector) Collect ¶
func (fc *FocusCollector) Collect(widget Widget, autoID string, ctx BuildContext)
Collect adds a focusable widget to the collection. The autoID is the position-based auto-generated ID from BuildContext. If the widget implements Identifiable with a non-empty ID, that is used instead. Disabled widgets (ctx.IsDisabled() == true) are skipped and cannot receive focus.
func (*FocusCollector) CurrentTrapID ¶
func (fc *FocusCollector) CurrentTrapID() string
CurrentTrapID returns the ID of the innermost active focus trap, or "" if none.
func (*FocusCollector) FirstFocusableIDAfter ¶
func (fc *FocusCollector) FirstFocusableIDAfter(index int) string
FirstFocusableIDAfter returns the ID of the first focusable widget collected after the given index that reports IsFocusable() == true. Returns empty string if no such focusable exists.
func (*FocusCollector) Focusables ¶
func (fc *FocusCollector) Focusables() []FocusableEntry
Focusables returns all collected focusable entries.
func (*FocusCollector) Len ¶
func (fc *FocusCollector) Len() int
Len returns the number of focusables collected so far.
func (*FocusCollector) PopAncestor ¶
func (fc *FocusCollector) PopAncestor()
PopAncestor removes the last widget from the ancestor chain. Called when exiting a widget that implements KeyHandler or KeybindProvider.
func (*FocusCollector) PopTrap ¶
func (fc *FocusCollector) PopTrap()
PopTrap removes the innermost focus trap scope from the stack.
func (*FocusCollector) PushAncestor ¶
func (fc *FocusCollector) PushAncestor(widget Widget)
PushAncestor adds a widget to the ancestor chain. Called when entering a widget that implements KeyHandler or KeybindProvider.
func (*FocusCollector) PushTrap ¶
func (fc *FocusCollector) PushTrap(id string)
PushTrap pushes a focus trap scope onto the stack. Called when entering a widget that implements FocusTrapper with TrapsFocus() == true.
func (*FocusCollector) Reset ¶
func (fc *FocusCollector) Reset()
Reset clears the collected focusables for a new render pass.
func (*FocusCollector) ShouldTrackAncestor ¶
func (fc *FocusCollector) ShouldTrackAncestor(widget Widget) bool
ShouldTrackAncestor returns true if the widget should be added to the ancestor chain. A widget is tracked if it implements KeyHandler or KeybindProvider.
type FocusManager ¶
type FocusManager struct {
// contains filtered or unexported fields
}
FocusManager tracks the currently focused widget and handles navigation.
func NewFocusManager ¶
func NewFocusManager() *FocusManager
NewFocusManager creates a new focus manager.
func (*FocusManager) ActiveKeybinds ¶
func (fm *FocusManager) ActiveKeybinds() []Keybind
ActiveKeybinds returns all declarative keybindings currently active based on the focused widget and its ancestors, plus root widget keybinds. Keybindings are returned in order from focused widget to root, matching the order they would be checked when handling key events.
If the focused widget implements KeyCapturer, ancestor keybinds are filtered to exclude keys that the focused widget captures (since those keys won't bubble up to trigger the ancestor keybinds).
func (*FocusManager) FocusByID ¶
func (fm *FocusManager) FocusByID(id string)
FocusByID sets focus to the widget with the given ID.
func (*FocusManager) FocusNext ¶
func (fm *FocusManager) FocusNext()
FocusNext moves focus to the next focusable widget (Tab). If the focused widget is within a focus trap, cycling is constrained to that trap.
func (*FocusManager) FocusPrevious ¶
func (fm *FocusManager) FocusPrevious()
FocusPrevious moves focus to the previous focusable widget (Shift+Tab). If the focused widget is within a focus trap, cycling is constrained to that trap.
func (*FocusManager) Focused ¶
func (fm *FocusManager) Focused() Focusable
Focused returns the currently focused widget, or nil if none.
func (*FocusManager) FocusedID ¶
func (fm *FocusManager) FocusedID() string
FocusedID returns the ID of the focused widget ("" if none).
func (*FocusManager) HandleKey ¶
func (fm *FocusManager) HandleKey(event KeyEvent) bool
HandleKey routes a key event to the focused widget, bubbling up if not handled. For each widget in the chain, declarative keybindings (KeybindProvider) are checked first, then the imperative OnKey handler. Returns true if the key was handled.
func (*FocusManager) IsInModalTrap ¶
func (fm *FocusManager) IsInModalTrap() bool
IsInModalTrap returns true if the currently focused widget is inside a focus trap. Used to avoid re-saving focus on every render when a modal is already open.
func (*FocusManager) RestoreFocus ¶
func (fm *FocusManager) RestoreFocus() string
RestoreFocus pops the most recently saved focus ID from the stack and moves focus back to it. Returns the restored ID, or "" if the stack was empty.
func (*FocusManager) SaveFocus ¶
func (fm *FocusManager) SaveFocus()
SaveFocus pushes the current focused ID onto the saved focus stack. Call this before moving focus into a modal so the prior focus can be restored when the modal closes via RestoreFocus.
func (*FocusManager) SetFocusables ¶
func (fm *FocusManager) SetFocusables(focusables []FocusableEntry)
SetFocusables updates the list of focusable widgets. Called after each render to update the tab order.
func (*FocusManager) SetRootWidget ¶
func (fm *FocusManager) SetRootWidget(root Widget)
SetRootWidget sets the root widget for including root-level keybinds.
type FocusTrap ¶
type FocusTrap struct {
// ID is a unique identifier for this focus trap scope.
// Required when Active is true.
ID string
// Active controls whether focus trapping is enabled.
// When false, the FocusTrap is fully transparent and focus cycles globally.
Active bool
// Child is the widget subtree in which focus is trapped.
Child Widget
}
FocusTrap is a transparent wrapper widget that traps focus within its subtree. When Active is true, Tab/Shift+Tab cycling is constrained to focusable widgets within the FocusTrap's child tree. When Active is false, focus cycles globally as normal.
FocusTrap is transparent to layout — it delegates entirely to its Child.
Example - trapping focus within a dialog:
FocusTrap{
ID: "dialog-trap",
Active: true,
Child: Column{
Children: []Widget{
TextInput{ID: "name", State: nameState},
Button{ID: "submit", Label: "Submit", OnPress: submit},
},
},
}
func (FocusTrap) Build ¶
func (ft FocusTrap) Build(ctx BuildContext) Widget
Build returns the child widget directly. FocusTrap is handled as a transparent wrapper by BuildRenderTree, so this method is only called as a fallback.
func (FocusTrap) TrapsFocus ¶
TrapsFocus returns true when the focus trap is active.
type FocusTrapper ¶
type FocusTrapper interface {
TrapsFocus() bool
}
FocusTrapper is implemented by widgets that trap focus within their subtree. Tab/Shift+Tab cycling is constrained to focusables within the innermost active trap.
type Focusable ¶
type Focusable interface {
// OnKey is called when the widget has focus and a key is pressed.
// Return true if the key was handled, false to propagate.
OnKey(event KeyEvent) bool
// IsFocusable returns whether this widget can currently receive focus.
// This allows widgets to dynamically enable/disable focus.
IsFocusable() bool
}
Focusable is implemented by widgets that can receive keyboard focus.
type FocusableEntry ¶
type FocusableEntry struct {
ID string
Focusable Focusable
// Ancestors is the chain of widgets from root to this widget's parent
// that implement KeyHandler or KeybindProvider.
// Used for bubbling key events up the tree.
Ancestors []Widget
// TrapID is the ID of the innermost FocusTrapper ancestor, or "" if none.
// Used to constrain Tab/Shift+Tab cycling within a trap scope.
TrapID string
}
FocusableEntry pairs a focusable widget with its identity and ancestor chain.
type FrameAnimation ¶
type FrameAnimation[T any] struct { // contains filtered or unexported fields }
FrameAnimation cycles through discrete frames at a given interval. Useful for spinners, loading indicators, and sprite animations.
func NewFrameAnimation ¶
func NewFrameAnimation[T any](config FrameAnimationConfig[T]) *FrameAnimation[T]
NewFrameAnimation creates a new frame-based animation. Panics if Frames is empty.
func (*FrameAnimation[T]) Advance ¶
func (fa *FrameAnimation[T]) Advance(dt time.Duration) bool
Advance implements the Animator interface.
func (*FrameAnimation[T]) Get ¶
func (fa *FrameAnimation[T]) Get() T
Get returns the current frame directly without subscribing.
func (*FrameAnimation[T]) Index ¶
func (fa *FrameAnimation[T]) Index() int
Index returns the current frame index.
func (*FrameAnimation[T]) IsRunning ¶
func (fa *FrameAnimation[T]) IsRunning() bool
IsRunning returns true if the animation is currently active.
func (*FrameAnimation[T]) Reset ¶
func (fa *FrameAnimation[T]) Reset()
Reset restarts from the first frame. Does not automatically start the animation; call Start() after Reset().
func (*FrameAnimation[T]) Start ¶
func (fa *FrameAnimation[T]) Start()
Start begins the frame animation. If called before the app is running, the animation will automatically start when the controller becomes available (on first Value() access).
func (*FrameAnimation[T]) Value ¶
func (fa *FrameAnimation[T]) Value() AnySignal[T]
Value returns a signal containing the current frame. Call Value().Get() during Build() for reactive updates.
type FrameAnimationConfig ¶
type FrameAnimationConfig[T any] struct { Frames []T // Required: frames to cycle through FrameTime time.Duration // Time per frame Loop bool // Whether to loop continuously OnComplete func() // Called when non-looping animation ends }
FrameAnimationConfig configures a FrameAnimation.
type Gradient ¶
type Gradient struct {
// contains filtered or unexported fields
}
Gradient represents a smooth color gradient between multiple color stops. It implements ColorProvider to enable gradient backgrounds via Style.BackgroundColor.
Example:
Style{BackgroundColor: NewGradient(Hex("#0F172A"), Hex("#1E293B")).WithAngle(45)}
func NewGradient ¶
NewGradient creates a gradient from two or more colors. Colors are evenly distributed along the gradient. Default angle is 0 (top-to-bottom). Use WithAngle() to change direction.
func (Gradient) At ¶
At returns the color at position t along the gradient. t should be in range [0, 1] where 0 is the first color and 1 is the last.
func (Gradient) ColorAt ¶
ColorAt returns the interpolated color at position (x, y) within the region. This implements ColorProvider.
func (Gradient) IsSet ¶
IsSet returns true if the gradient has colors. This implements ColorProvider.
type Highlighter ¶
type Highlighter interface {
Highlight(text string, graphemes []string) []TextHighlight
}
Highlighter produces highlights for text content.
type HighlighterFunc ¶
type HighlighterFunc func(text string, graphemes []string) []TextHighlight
HighlighterFunc adapts a function to the Highlighter interface.
func (HighlighterFunc) Highlight ¶
func (f HighlighterFunc) Highlight(text string, graphemes []string) []TextHighlight
Highlight implements the Highlighter interface.
type HorizontalAlignment ¶
type HorizontalAlignment int
HorizontalAlignment specifies horizontal positioning within available space.
const ( // HAlignStart aligns content at the start (left) of the available space. HAlignStart HorizontalAlignment = iota // HAlignCenter centers content horizontally. HAlignCenter // HAlignEnd aligns content at the end (right) of the available space. HAlignEnd )
type HoverEvent ¶ added in v0.3.0
type HoverEvent struct {
Type HoverEventType
// Absolute screen coordinates of the pointer.
X, Y int
// Local coordinates relative to the target widget's bounds.
LocalX, LocalY int
Button uv.MouseButton
Mod uv.KeyMod
// WidgetID is the ID of the target widget receiving this event.
WidgetID string
// PreviousWidgetID is the widget hovered before the transition.
PreviousWidgetID string
// NextWidgetID is the widget hovered after the transition.
NextWidgetID string
}
HoverEvent describes a pointer hover transition for a widget.
type HoverEventType ¶ added in v0.3.0
type HoverEventType int
HoverEventType identifies the hover transition kind.
const ( // HoverEnter indicates the pointer entered a widget. HoverEnter HoverEventType = iota // HoverLeave indicates the pointer left a widget. HoverLeave )
type Hoverable ¶
type Hoverable interface {
OnHover(event HoverEvent)
}
Hoverable is implemented by widgets that respond to hover transitions.
type Identifiable ¶
type Identifiable interface {
WidgetID() string
}
Identifiable is implemented by widgets that provide an identity. If WidgetID() returns a non-empty string, that ID takes precedence over the position-based AutoID for focus management and hit testing. The ID should be unique among siblings and persist across rebuilds.
type InsertStrategy ¶
type InsertStrategy func(text string, cursor int, suggestion Suggestion, triggerPos int) (newText string, newCursor int)
InsertStrategy defines how a suggestion is inserted into the text. It receives the current text, cursor position, the selected suggestion, and the trigger position (or -1 if no trigger), and returns the new text and new cursor position.
var InsertAtCursor InsertStrategy = func(text string, cursor int, suggestion Suggestion, triggerPos int) (string, int) { value := suggestion.Value if value == "" { value = suggestion.Label } runes := []rune(text) if cursor > len(runes) { cursor = len(runes) } if cursor < 0 { cursor = 0 } newRunes := append([]rune{}, runes[:cursor]...) newRunes = append(newRunes, []rune(value)...) newRunes = append(newRunes, runes[cursor:]...) return string(newRunes), cursor + utf8.RuneCountInString(value) }
InsertAtCursor inserts the suggestion value at the cursor position.
var InsertFromTrigger InsertStrategy = func(text string, cursor int, suggestion Suggestion, triggerPos int) (string, int) { value := suggestion.Value if value == "" { value = suggestion.Label } runes := []rune(text) if triggerPos < 0 { triggerPos = 0 } if triggerPos > len(runes) { triggerPos = len(runes) } if cursor > len(runes) { cursor = len(runes) } newRunes := append([]rune{}, runes[:triggerPos]...) newRunes = append(newRunes, []rune(value)...) newRunes = append(newRunes, runes[cursor:]...) return string(newRunes), triggerPos + utf8.RuneCountInString(value) }
InsertFromTrigger replaces text from the trigger position to cursor with the suggestion. If no trigger position, replaces from start.
var InsertReplace InsertStrategy = func(text string, cursor int, suggestion Suggestion, triggerPos int) (string, int) { value := suggestion.Value if value == "" { value = suggestion.Label } return value, utf8.RuneCountInString(value) }
InsertReplace replaces the entire text with the suggestion value.
var InsertReplaceWord InsertStrategy = func(text string, cursor int, suggestion Suggestion, triggerPos int) (string, int) { value := suggestion.Value if value == "" { value = suggestion.Label } runes := []rune(text) if cursor > len(runes) { cursor = len(runes) } if cursor < 0 { cursor = 0 } wordStart := cursor for wordStart > 0 && !unicode.IsSpace(runes[wordStart-1]) { wordStart-- } wordEnd := cursor for wordEnd < len(runes) && !unicode.IsSpace(runes[wordEnd]) { wordEnd++ } newRunes := append([]rune{}, runes[:wordStart]...) newRunes = append(newRunes, []rune(value)...) newRunes = append(newRunes, runes[wordEnd:]...) return string(newRunes), wordStart + utf8.RuneCountInString(value) }
InsertReplaceWord replaces the current word (delimited by whitespace) with the suggestion.
type Interpolator ¶
Interpolator defines how to interpolate between two values of type T. The parameter t is in range [0, 1] where 0 returns from and 1 returns to.
type KeyCapturer ¶
type KeyCapturer interface {
// CapturesKey returns true if this widget captures the given key,
// preventing it from bubbling to ancestors.
CapturesKey(key string) bool
}
KeyCapturer is implemented by widgets that capture certain key events, preventing them from bubbling to ancestors. When a KeyCapturer has focus, ancestor keybinds are filtered based on CapturesKey() - only keybinds for keys that are NOT captured will be shown in the KeybindBar.
For example, a text input captures printable characters (typing "q" inserts text rather than triggering a "quit" keybind), but allows "escape" or "ctrl+j" to bubble up.
type KeyEvent ¶
type KeyEvent struct {
// contains filtered or unexported fields
}
KeyEvent wraps a key press event from ultraviolet.
func (KeyEvent) MatchString ¶
MatchString returns true if the key matches one of the given strings. Examples: "enter", "tab", "a", "ctrl+a", "shift+enter", "alt+tab"
type KeyHandler ¶
KeyHandler is implemented by widgets that want to handle key events. Unlike Focusable, any widget in the tree can implement this to receive bubbling key events from focused descendants.
type Keybind ¶
type Keybind struct {
// Key is the key pattern to match, e.g., "ctrl+s", "enter", "shift+tab"
Key string
// Name is a short display name for the binding, e.g., "Save", "Submit"
Name string
// Action is the callback to execute when the keybinding is triggered
Action func()
// Hidden prevents this keybind from appearing in KeybindBar.
// Use for internal bindings that shouldn't be displayed to users.
Hidden bool
}
Keybind represents a single declarative keybinding. It associates a key pattern with a display name and action callback.
type KeybindBar ¶
type KeybindBar struct {
Style Style // Optional styling (background, padding, etc.)
Width Dimension // Width dimension (default: Fr(1) to fill available width)
Height Dimension // Height dimension (default: Cells(1) for single-line bar)
// FormatKey transforms key strings for display. If nil, uses minimal
// normalization (e.g., " " → "space"). Use preset formatters like
// FormatKeyCaret, FormatKeyEmacs, FormatKeyVim, or FormatKeyVerbose,
// or provide a custom function.
FormatKey func(string) string
}
KeybindBar displays available keybinds based on the currently focused widget. It automatically updates when focus changes, showing keybinds from the focused widget and its ancestors in the widget tree.
Keybinds are deduplicated by key, with the focused widget taking precedence over ancestors. Keybinds with Hidden=true are not displayed.
Consecutive keybinds with the same Name are grouped together, displaying their keys joined with "/" (e.g., "enter/space Press").
func (KeybindBar) Build ¶
func (f KeybindBar) Build(ctx BuildContext) Widget
Build constructs the keybind bar by collecting active keybinds from context.
func (KeybindBar) GetDimensions ¶
func (f KeybindBar) GetDimensions() (width, height Dimension)
GetDimensions returns the width and height dimension preferences. Width defaults to Auto if not explicitly set, sizing to content. Height defaults to Cells(1) if not explicitly set, as KeybindBar is a single-line widget.
type KeybindProvider ¶
type KeybindProvider interface {
Keybinds() []Keybind
}
KeybindProvider is implemented by widgets that declare keybindings. Widgets implementing this interface can define their keybindings declaratively, allowing the framework to query and display them (e.g., in a footer).
type LabelVariant ¶
type LabelVariant int
LabelVariant represents the semantic color variant for a Label.
const ( LabelDefault LabelVariant = iota LabelPrimary LabelSecondary LabelAccent LabelSuccess LabelError LabelWarning LabelInfo )
type LayoutMetrics ¶
type LayoutMetrics struct {
// contains filtered or unexported fields
}
LayoutMetrics provides convenient access to computed layout information. Child bounds are returned in the parent's content coordinate space.
func (LayoutMetrics) Box ¶
func (m LayoutMetrics) Box() layout.BoxModel
Box returns the computed BoxModel for this widget.
func (LayoutMetrics) ChildBounds ¶
func (m LayoutMetrics) ChildBounds(i int) (Rect, bool)
ChildBounds returns the child's border-box bounds in content coordinates.
func (LayoutMetrics) ChildCount ¶
func (m LayoutMetrics) ChildCount() int
ChildCount returns the number of positioned children.
func (LayoutMetrics) ChildHeight ¶
func (m LayoutMetrics) ChildHeight(i int) (int, bool)
ChildHeight returns the child's border-box height in cells.
func (LayoutMetrics) ChildLayout ¶
func (m LayoutMetrics) ChildLayout(i int) (layout.ComputedLayout, bool)
ChildLayout returns the computed layout for the child at index i.
func (LayoutMetrics) ChildMarginBounds ¶
func (m LayoutMetrics) ChildMarginBounds(i int) (Rect, bool)
ChildMarginBounds returns the child's margin-box bounds in content coordinates.
type LayoutNodeBuilder ¶
type LayoutNodeBuilder interface {
BuildLayoutNode(ctx BuildContext) layout.LayoutNode
}
LayoutNodeBuilder is implemented by widgets that can build a layout node for themselves. This enables integration with the new layout system in the layout package.
type LayoutObserver ¶
type LayoutObserver interface {
OnLayout(ctx BuildContext, metrics LayoutMetrics)
}
LayoutObserver is implemented by widgets that want access to computed layout data. OnLayout is called after layout is computed for the widget, before child render trees are built. Use this to read resolved child positions/sizes without re-measuring.
type Layoutable ¶
type Layoutable interface {
Layout(ctx BuildContext, constraints Constraints) Size
}
Layoutable is implemented by widgets that can compute their size given constraints and perform layout on their children.
type LineHighlight ¶
type LineHighlight struct {
StartLine int // Line index (0-based, inclusive)
EndLine int // Line index (exclusive), -1 means to end
Style Style // Full style (supports background color)
}
LineHighlight represents a styled line range (TextArea only).
type List ¶
type List[T any] struct { ID string // Optional unique identifier DisableFocus bool // If true, prevent keyboard focus CursorStyle // Embedded - CursorPrefix/SelectedPrefix fields for customizable indicators State *ListState[T] // Required - holds items and cursor position OnSelect func(item T) // Callback invoked when Enter is pressed on an item OnCursorChange func(item T) // Callback invoked when cursor moves to a different item ScrollState *ScrollState // Optional state for scroll-into-view RenderItem func(item T, active bool, selected bool) Widget // Function to render each item (uses default if nil) RenderItemWithMatch func(item T, active bool, selected bool, match MatchResult) Widget // Optional render function with match data Filter *FilterState // Optional filter state for matching items MatchItem func(item T, query string, options FilterOptions) MatchResult // Optional matcher for filtering/highlighting ItemHeight int // Optional uniform item height override (default 0 = layout metrics / fallback 1) MultiSelect bool // Enable multi-select mode (space to toggle, shift+move to extend) Width Dimension // Deprecated: use Style.Width Height Dimension // Deprecated: use Style.Height Style Style // Optional styling Click func(MouseEvent) // Optional callback invoked when clicked MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed MouseUp func(MouseEvent) // Optional callback invoked when mouse is released Hover func(HoverEvent) // Optional callback invoked when hover state changes Blur func() // Optional callback invoked when focus leaves this widget }
List is a generic focusable widget that displays a navigable list of items. It builds a Column of widgets, with the active item (cursor position) highlighted. Use with Scrollable and a shared ScrollState to enable scroll-into-view.
Example usage:
state := terma.NewListState([]string{"Item 1", "Item 2", "Item 3"})
list := terma.List[string]{
State: state,
OnSelect: func(item string) {
// Handle selection
},
}
// Add item at runtime:
state.Append("Item 4")
// Remove item at runtime:
state.RemoveAt(0)
func (List[T]) Build ¶
func (l List[T]) Build(ctx BuildContext) Widget
Build returns a Column of widgets, each rendered via RenderItem.
func (List[T]) CursorItem ¶
func (l List[T]) CursorItem() T
CursorItem returns the item at the current cursor position. Returns the zero value of T if the list is empty or state is nil. Deprecated: Use State.SelectedItem() instead.
func (List[T]) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences. Implements the Dimensioned interface.
func (List[T]) GetStyle ¶
GetStyle returns the style of the list widget. Implements the Styled interface.
func (List[T]) IsFocusable ¶
IsFocusable returns true to allow keyboard navigation. Implements the Focusable interface.
func (List[T]) OnBlur ¶
func (l List[T]) OnBlur()
OnBlur is called when this widget loses keyboard focus. Implements the Blurrable interface.
func (List[T]) OnClick ¶
func (l List[T]) OnClick(event MouseEvent)
OnClick is called when the widget is clicked. Implements the Clickable interface.
func (List[T]) OnHover ¶
func (l List[T]) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions. Implements the Hoverable interface.
func (List[T]) OnKey ¶
OnKey handles keys not covered by declarative keybindings. Implements the Focusable interface.
func (List[T]) OnMouseDown ¶
func (l List[T]) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (List[T]) OnMouseUp ¶
func (l List[T]) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
type ListState ¶
type ListState[T any] struct { Items AnySignal[[]T] // Reactive list data CursorIndex Signal[int] // Cursor position Selection AnySignal[map[int]struct{}] // Selected item indices (for multi-select) // contains filtered or unexported fields }
ListState holds the state for a List widget. It is the source of truth for items and cursor position, and must be provided to List. Items is a reactive Signal - changes trigger automatic re-renders.
func NewListState ¶
NewListState creates a new ListState with the given initial items.
func (*ListState[T]) Append ¶
func (s *ListState[T]) Append(item T)
Append adds an item to the end of the list.
func (*ListState[T]) ApplyFilter ¶
func (s *ListState[T]) ApplyFilter(filter *FilterState, matchItem func(item T, query string, options FilterOptions) MatchResult) int
ApplyFilter applies a filter to the items and caches the results. Returns the number of items that match the filter. The cached results are used by List.Build() to avoid re-filtering.
func (*ListState[T]) ClearAnchor ¶
func (s *ListState[T]) ClearAnchor()
ClearAnchor removes the anchor point.
func (*ListState[T]) ClearSelection ¶
func (s *ListState[T]) ClearSelection()
ClearSelection removes all items from the selection.
func (*ListState[T]) FilteredCount ¶
FilteredCount returns the number of items after filtering. Returns total item count if no filter has been applied.
func (*ListState[T]) GetItems ¶
func (s *ListState[T]) GetItems() []T
GetItems returns the current list data (without subscribing to changes).
func (*ListState[T]) InsertAt ¶
InsertAt inserts an item at the specified index. If index is out of bounds, it's clamped to valid range.
func (*ListState[T]) IsSelected ¶
IsSelected returns true if the item at the given index is selected.
func (*ListState[T]) Prepend ¶
func (s *ListState[T]) Prepend(item T)
Prepend adds an item to the beginning of the list.
func (*ListState[T]) RemoveAt ¶
RemoveAt removes the item at the specified index. Returns true if an item was removed, false if index was out of bounds.
func (*ListState[T]) RemoveWhere ¶
RemoveWhere removes all items matching the predicate. Returns the number of items removed.
func (*ListState[T]) SelectAll ¶
func (s *ListState[T]) SelectAll()
SelectAll selects all items in the list.
func (*ListState[T]) SelectFirst ¶
func (s *ListState[T]) SelectFirst()
SelectFirst moves cursor to the first item.
func (*ListState[T]) SelectIndex ¶
SelectIndex sets cursor to a specific index, clamped to valid range.
func (*ListState[T]) SelectLast ¶
func (s *ListState[T]) SelectLast()
SelectLast moves cursor to the last item.
func (*ListState[T]) SelectNext ¶
func (s *ListState[T]) SelectNext()
SelectNext moves cursor to the next item.
func (*ListState[T]) SelectPrevious ¶
func (s *ListState[T]) SelectPrevious()
SelectPrevious moves cursor to the previous item.
func (*ListState[T]) SelectRange ¶
SelectRange selects all items between from and to (inclusive).
func (*ListState[T]) SelectedIndices ¶
SelectedIndices returns the indices of all selected items in ascending order.
func (*ListState[T]) SelectedItem ¶
SelectedItem returns the currently selected item (if any).
func (*ListState[T]) SelectedItems ¶
func (s *ListState[T]) SelectedItems() []T
SelectedItems returns all currently selected items.
func (*ListState[T]) SetItems ¶
func (s *ListState[T]) SetItems(items []T)
SetItems replaces all items and clamps cursor to valid range.
func (*ListState[T]) ToggleSelection ¶
ToggleSelection toggles the selection state of the item at the given index.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger provides debug logging to a file. Logs are written to terma.log in the current directory.
type MainAxisAlign ¶
type MainAxisAlign int
MainAxisAlign specifies how children are aligned along the main axis. For Row, main axis is horizontal. For Column, main axis is vertical.
const ( // MainAxisStart aligns children at the start (default). MainAxisStart MainAxisAlign = iota // MainAxisCenter centers children along the main axis. MainAxisCenter // MainAxisEnd aligns children at the end. MainAxisEnd )
type MatchRange ¶
MatchRange defines a matched substring range [Start, End) in bytes.
type MatchResult ¶
type MatchResult struct {
Matched bool
Ranges []MatchRange
}
MatchResult represents match status and highlight ranges.
func MatchString ¶
func MatchString(text string, query string, options FilterOptions) MatchResult
MatchString matches query against text using the provided options.
type Menu ¶
type Menu struct {
ID string // Optional unique identifier
DisableFocus bool // If true, prevent keyboard focus
State *MenuState // Required
// Positioning (choose one approach)
AnchorID string // Anchor to widget (dropdown style)
Anchor AnchorPoint // Where to anchor (default: AnchorBottomLeft)
Position FloatPosition
Offset Offset
// Callbacks
OnSelect func(item MenuItem) // Called when item selected
OnDismiss func() // Called when menu should close
// Styling
Width Dimension // Deprecated: use Style.Width
Style Style // Container style
}
Menu is a convenience widget for dropdown/context menus. It composes Floating + list rendering internally.
func (Menu) Build ¶
func (m Menu) Build(ctx BuildContext) Widget
Build renders the menu as a floating overlay.
func (Menu) IsFocusable ¶
IsFocusable returns true to allow keyboard navigation.
type MenuItem ¶
type MenuItem struct {
Label string // Display text
Shortcut string // Optional hint (e.g., "Ctrl+S")
Action func() // Callback when selected (ignored if Children is set)
Children []MenuItem // Submenu items (opens on right arrow)
Disabled bool // Shown but not selectable
Divider string // Divider title (empty renders a plain separator)
}
MenuItem represents a menu item with optional submenu.
func (MenuItem) IsSelectable ¶
IsSelectable returns true if the item can be focused/selected.
type MenuState ¶
type MenuState struct {
// contains filtered or unexported fields
}
MenuState holds the state for a Menu widget.
func NewMenuState ¶
NewMenuState creates a new MenuState with the given items.
func (*MenuState) CloseSubmenu ¶
func (s *MenuState) CloseSubmenu()
CloseSubmenu closes any open submenu.
func (*MenuState) CursorIndex ¶
CursorIndex returns the current cursor position.
func (*MenuState) HasOpenSubmenu ¶
HasOpenSubmenu returns true if there is an open submenu.
func (*MenuState) OpenSubmenu ¶
OpenSubmenu opens the submenu for the given item index.
func (*MenuState) SelectedItem ¶
SelectedItem returns the currently selected item (if any).
func (*MenuState) SetCursorIndex ¶
SetCursorIndex sets the cursor position (clamped to valid range).
type MouseDownHandler ¶
type MouseDownHandler interface {
OnMouseDown(event MouseEvent)
}
MouseDownHandler is implemented by widgets that respond to mouse button presses.
type MouseEvent ¶
type MouseEvent struct {
X, Y int // Absolute screen coordinates
LocalX int // X offset within the widget (0 = left edge)
LocalY int // Y offset within the widget (0 = top edge)
Button uv.MouseButton
Mod uv.KeyMod
ClickCount int // 1=single, 2=double, 3=triple, etc
WidgetID string
}
MouseEvent wraps a mouse interaction with click-chain metadata.
type MouseMoveHandler ¶
type MouseMoveHandler interface {
OnMouseMove(event MouseEvent)
}
MouseMoveHandler is implemented by widgets that respond to mouse movement during drag.
type MouseUpHandler ¶
type MouseUpHandler interface {
OnMouseUp(event MouseEvent)
}
MouseUpHandler is implemented by widgets that respond to mouse button releases.
type Positioned ¶
type Positioned struct {
Top *int // Offset from top edge (nil = not constrained)
Right *int // Offset from right edge (nil = not constrained)
Bottom *int // Offset from bottom edge (nil = not constrained)
Left *int // Offset from left edge (nil = not constrained)
Child Widget // The child widget to position
}
Positioned wraps a child widget to position it within a Stack using edge offsets. Use nil for edges that should not constrain the child.
Positioning rules:
- If both Top and Bottom are set, the child's height is computed as stack height - top - bottom
- If both Left and Right are set, the child's width is computed as stack width - left - right
- Otherwise, the child sizes naturally and is positioned from the specified edges
func PositionedAt ¶
func PositionedAt(top, left int, child Widget) Positioned
PositionedAt creates a Positioned at specific top-left offsets.
func PositionedFill ¶
func PositionedFill(child Widget) Positioned
PositionedFill creates a Positioned that fills the entire Stack.
func (Positioned) Build ¶
func (p Positioned) Build(ctx BuildContext) Widget
Build returns itself as Positioned is handled specially by Stack.
type PrintOptions ¶
type PrintOptions struct {
Width int // 0 = auto-detect or default 80
Height int // 0 = auto-detect or default 24
Writer io.Writer // nil = os.Stdout
NoColor bool // Force plain text output (no ANSI)
TrailingNewline bool // Add newline after output (default: true)
AutoHeight bool // Use widget's computed height instead of buffer height (default: true)
}
PrintOptions configures widget printing behavior.
func DefaultPrintOptions ¶
func DefaultPrintOptions() PrintOptions
DefaultPrintOptions returns sensible defaults for printing.
type ProgressBar ¶
type ProgressBar struct {
ID string // Optional unique identifier
// Core fields
Progress float64 // 0.0 to 1.0
// Legacy dimensions
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
// Styling
Style Style // General styling (padding, margins, border)
FilledColor Color // Color of filled portion (default: theme Primary)
UnfilledColor Color // Color of unfilled portion (default: theme Surface)
}
ProgressBar displays a horizontal progress indicator. Progress is specified as a float64 from 0.0 (empty) to 1.0 (full). Uses Unicode block characters for smooth sub-character rendering.
Example:
ProgressBar{
Progress: 0.65,
Style: Style{Width: Cells(20)},
FilledColor: ctx.Theme().Primary,
}
func (ProgressBar) Build ¶
func (p ProgressBar) Build(ctx BuildContext) Widget
Build returns itself as ProgressBar is a leaf widget.
func (ProgressBar) BuildLayoutNode ¶
func (p ProgressBar) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this ProgressBar widget.
func (ProgressBar) GetContentDimensions ¶
func (p ProgressBar) GetContentDimensions() (width, height Dimension)
GetContentDimensions returns the width and height dimension preferences. Width defaults to Flex(1), Height defaults to Cells(1).
func (ProgressBar) GetStyle ¶
func (p ProgressBar) GetStyle() Style
GetStyle returns the style of the progress bar.
func (ProgressBar) Render ¶
func (p ProgressBar) Render(ctx *RenderContext)
Render draws the progress bar to the render context.
func (ProgressBar) WidgetID ¶
func (p ProgressBar) WidgetID() string
WidgetID returns the progress bar's unique identifier. Implements the Identifiable interface.
type Rect ¶
Rect represents a rectangular region in terminal coordinates.
type RenderContext ¶
type RenderContext struct {
// Absolute position in terminal (may be outside clip for virtual/scrolled positioning)
X, Y int
// Available size for this widget's content
Width, Height int
// contains filtered or unexported fields
}
RenderContext provides drawing primitives for widgets. It tracks the current region where the widget should render.
func NewRenderContext ¶
func NewRenderContext(terminal CellBuffer, width, height int, fc *FocusCollector, fm *FocusManager, bc BuildContext, wr *WidgetRegistry) *RenderContext
NewRenderContext creates a root render context for the terminal.
func (*RenderContext) ClipBounds ¶
func (ctx *RenderContext) ClipBounds() Rect
ClipBounds returns the current clip rect.
func (*RenderContext) DrawBackdrop ¶
func (ctx *RenderContext) DrawBackdrop(x, y, width, height int, backdrop ColorProvider)
DrawBackdrop applies a semi-transparent overlay over existing content. Unlike FillRect, this preserves the underlying characters and blends the backdrop color over both foreground and background colors. This creates a true transparency effect where text behind is still visible.
func (*RenderContext) DrawBorder ¶
func (ctx *RenderContext) DrawBorder(x, y, width, height int, border Border)
DrawBorder draws a border around a rectangular region. The border is drawn at the edges of the specified rectangle.
func (*RenderContext) DrawSpan ¶
func (ctx *RenderContext) DrawSpan(x, y int, span Span, baseStyle Style) int
DrawSpan draws a styled span at the given position relative to this context. The baseStyle provides default colors when span style doesn't specify them. Returns the number of characters drawn (for positioning subsequent spans).
func (*RenderContext) DrawStyledText ¶
func (ctx *RenderContext) DrawStyledText(x, y int, text string, style Style)
DrawStyledText draws styled text at the given position relative to this context.
func (*RenderContext) DrawText ¶
func (ctx *RenderContext) DrawText(x, y int, text string)
DrawText draws text at the given position relative to this context.
func (*RenderContext) FillRect ¶
func (ctx *RenderContext) FillRect(x, y, width, height int, bgColor Color)
FillRect fills a rectangular region with a background color. If the color is semi-transparent, it blends with the inherited background.
func (*RenderContext) IsFocused ¶
func (ctx *RenderContext) IsFocused(widget Widget) bool
IsFocused returns true if the given widget currently has focus. Widgets with an explicit ID are matched by that ID; otherwise the position-based AutoID is used as a fallback.
func (*RenderContext) IsVisible ¶
func (ctx *RenderContext) IsVisible(absX, absY int) bool
IsVisible returns whether a point is within the clip rect.
func (*RenderContext) OverflowSubContext ¶
func (ctx *RenderContext) OverflowSubContext(xOffset, yOffset, width, height int) *RenderContext
OverflowSubContext creates a child context offset from this one that allows overflow. Unlike SubContext, this keeps the parent's clip rect instead of intersecting with child bounds. This allows children to render outside their container's bounds (e.g., Stack children with negative positioning like badges that overflow their parent).
func (*RenderContext) ScrolledSubContext ¶
func (ctx *RenderContext) ScrolledSubContext(xOffset, yOffset, width, height, scrollX, scrollY int) *RenderContext
ScrolledSubContext creates a child context with scroll offsets applied. The clip rect remains the viewport bounds, but content positions are offset. scrollX shifts content left and scrollY shifts content up.
func (*RenderContext) SubContext ¶
func (ctx *RenderContext) SubContext(xOffset, yOffset, width, height int) *RenderContext
SubContext creates a child context offset from this one. The child's clip rect is the intersection of the parent's clip rect and the child's bounds.
type RenderTree ¶
type RenderTree struct {
// Widget is the built widget (result of Build()).
// Used for calling Render() and extracting style.
Widget Widget
// EventWidget is the original widget (before Build()).
// Used for hit testing and event dispatch.
EventWidget Widget
// EventID is the ID used for hit testing and focus (explicit or auto).
EventID string
// Layout is the computed geometry for this widget.
// Contains BoxModel with all dimensions and insets.
Layout layout.ComputedLayout
// Children are the child render trees.
// Positions come from Layout.Children[i].X and Layout.Children[i].Y.
Children []RenderTree
}
RenderTree pairs a widget with its computed layout for rendering. This enables complete separation of layout and rendering phases: 1. Build phase: widget.Build() creates widget tree 2. Layout phase: BuildRenderTree() computes all positions 3. Render phase: renderTree() paints using computed geometry
func BuildRenderTree ¶
func BuildRenderTree(widget Widget, ctx BuildContext, constraints layout.Constraints, fc *FocusCollector) RenderTree
BuildRenderTree constructs the complete render tree with all layout computed. Focus collection also happens here, keeping the render phase pure painting.
type Renderable ¶
type Renderable interface {
Render(ctx *RenderContext)
}
Renderable is implemented by widgets that can render themselves.
type Renderer ¶
type Renderer struct {
// contains filtered or unexported fields
}
Renderer handles the widget tree rendering pipeline.
func NewRenderer ¶
func NewRenderer(terminal CellBuffer, width, height int, fm *FocusManager, focusedSignal AnySignal[Focusable], hoveredSignal AnySignal[Widget]) *Renderer
NewRenderer creates a new renderer for the given terminal.
func (*Renderer) FloatAt ¶
func (r *Renderer) FloatAt(x, y int) *FloatEntry
FloatAt returns the topmost float entry containing the point (x, y). Returns nil if no float contains the point.
func (*Renderer) FocusableAt ¶
func (r *Renderer) FocusableAt(x, y int) *WidgetEntry
FocusableAt returns the innermost focusable widget at the given coordinates. Returns nil if no focusable widget is at that position.
func (*Renderer) HasModalFloat ¶
HasModalFloat returns true if any float is modal.
func (*Renderer) ModalCount ¶
ModalCount returns the number of modal floats currently rendered.
func (*Renderer) Render ¶
func (r *Renderer) Render(root Widget) []FocusableEntry
Render renders the widget tree to the terminal and returns collected focusables. This uses the tree-based rendering path which builds the complete layout tree first, then renders using BoxModel utilities for clean separation of layout and painting.
func (*Renderer) RenderWithSize ¶
RenderWithSize renders the widget and returns the computed border-box dimensions. The border-box includes the widget's content, padding, and borders.
func (*Renderer) ScreenText ¶
ScreenText returns the current screen content as plain text. Each row is separated by a newline. Wide characters are handled correctly.
func (*Renderer) ScrollableAt ¶
func (r *Renderer) ScrollableAt(x, y int) *Scrollable
ScrollableAt returns the innermost Scrollable widget at the given coordinates. Returns nil if no Scrollable is at that position.
func (*Renderer) ScrollablesAt ¶
func (r *Renderer) ScrollablesAt(x, y int) []*Scrollable
ScrollablesAt returns all Scrollable widgets at the given coordinates, ordered from innermost to outermost.
func (*Renderer) TopFloat ¶
func (r *Renderer) TopFloat() *FloatEntry
TopFloat returns the topmost (last registered) float entry, or nil if none.
func (*Renderer) WidgetAt ¶
func (r *Renderer) WidgetAt(x, y int) *WidgetEntry
WidgetAt returns the topmost widget at the given terminal coordinates. Returns nil if no widget is at that position.
func (*Renderer) WidgetByID ¶
func (r *Renderer) WidgetByID(id string) *WidgetEntry
WidgetByID returns the widget entry with the given ID. Returns nil if no widget has that ID.
type Row ¶
type Row struct {
ID string // Optional unique identifier for the widget
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling (background color)
Spacing int // Space between children
MainAlign MainAxisAlign // Main axis (horizontal) alignment
CrossAlign CrossAxisAlign // Cross axis (vertical) alignment
Children []Widget
Click func(MouseEvent) // Optional callback invoked when clicked
MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed
MouseUp func(MouseEvent) // Optional callback invoked when mouse is released
Hover func(HoverEvent) // Optional callback invoked when hover state changes
}
Row arranges its children horizontally.
func (Row) Build ¶
func (r Row) Build(ctx BuildContext) Widget
Build returns itself as Row manages its own children.
func (Row) BuildLayoutNode ¶
func (r Row) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this Row widget. Implements the LayoutNodeBuilder interface.
func (Row) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences.
func (Row) OnClick ¶
func (r Row) OnClick(event MouseEvent)
OnClick is called when the widget is clicked. Implements the Clickable interface.
func (Row) OnHover ¶
func (r Row) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions. Implements the Hoverable interface.
func (Row) OnMouseDown ¶
func (r Row) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (Row) OnMouseUp ¶
func (r Row) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
func (Row) Render ¶
func (r Row) Render(ctx *RenderContext)
Render is a no-op for Row when using the RenderTree-based rendering path. Child positioning is handled by renderTree() which uses the computed layout. Row has no content of its own to render - it's purely a layout container.
type SVGOptions ¶
type SVGOptions struct {
FontFamily string // Default: "Menlo, Monaco, Consolas, monospace"
FontSize int // Default: 14
LineHeight float64 // Default: 1.4
CellWidth float64 // Default: calculated from font size (fontSize * 0.6)
Background Color // Default: black
Padding int // Default: 8
}
SVGOptions configures SVG output generation.
func DefaultSVGOptions ¶
func DefaultSVGOptions() SVGOptions
DefaultSVGOptions returns sensible defaults for SVG generation.
type ScrollState ¶
type ScrollState struct {
OffsetX Signal[int] // Current horizontal scroll offset
Offset Signal[int] // Current vertical scroll offset
// PinToBottom enables auto-scroll when content grows while at bottom.
// Scrolling up breaks the pin; scrolling to bottom re-engages it.
PinToBottom bool
// OnScrollUp is called when ScrollUp is invoked with the number of lines.
// If it returns true, the default viewport scrolling is suppressed.
// Use this for selection-first scrolling (e.g., in List widget).
OnScrollUp func(lines int) bool
// OnScrollDown is called when ScrollDown is invoked with the number of lines.
// If it returns true, the default viewport scrolling is suppressed.
// Use this for selection-first scrolling (e.g., in List widget).
OnScrollDown func(lines int) bool
// OnScrollLeft is called when ScrollLeft is invoked with the number of columns.
// If it returns true, the default viewport scrolling is suppressed.
OnScrollLeft func(cols int) bool
// OnScrollRight is called when ScrollRight is invoked with the number of columns.
// If it returns true, the default viewport scrolling is suppressed.
OnScrollRight func(cols int) bool
// contains filtered or unexported fields
}
ScrollState holds scroll state for a Scrollable widget. It is the source of truth for scroll position, and must be provided to Scrollable. Share the same state between Scrollable and child widgets that need to control scroll position (e.g., List scrolling selection into view).
Example usage:
scrollState := terma.NewScrollState()
scrollable := terma.Scrollable{State: scrollState, ...}
list := terma.List[string]{ScrollState: scrollState, ...}
func NewScrollState ¶
func NewScrollState() *ScrollState
NewScrollState creates a new scroll state with initial offset of 0. isPinned starts true so that initial content (offset 0) is considered "at bottom".
func (*ScrollState) GetOffset ¶
func (s *ScrollState) GetOffset() int
GetOffset returns the current scroll offset (without subscribing).
func (*ScrollState) GetOffsetX ¶
func (s *ScrollState) GetOffsetX() int
GetOffsetX returns the current horizontal scroll offset (without subscribing).
func (*ScrollState) IsAtBottom ¶
func (s *ScrollState) IsAtBottom() bool
IsAtBottom returns true if currently scrolled to the bottom.
func (*ScrollState) IsPinned ¶
func (s *ScrollState) IsPinned() bool
IsPinned returns true if PinToBottom is enabled and currently pinned.
func (*ScrollState) ScrollDown ¶
func (s *ScrollState) ScrollDown(lines int) bool
ScrollDown scrolls down by the given number of lines. Returns true if scrolling was handled (callback handled it or offset changed). Returns false if already at the bottom and no callback handled it. If OnScrollDown is set and returns true, viewport scrolling is suppressed. If PinToBottom is enabled, reaching the bottom re-engages the pin.
func (*ScrollState) ScrollLeft ¶
func (s *ScrollState) ScrollLeft(cols int) bool
ScrollLeft scrolls left by the given number of columns. Returns true if scrolling was handled (callback handled it or offset changed). Returns false if already at the left edge and no callback handled it.
func (*ScrollState) ScrollRight ¶
func (s *ScrollState) ScrollRight(cols int) bool
ScrollRight scrolls right by the given number of columns. Returns true if scrolling was handled (callback handled it or offset changed). Returns false if already at the right edge and no callback handled it.
func (*ScrollState) ScrollToBottom ¶
func (s *ScrollState) ScrollToBottom()
ScrollToBottom scrolls to the bottom and re-engages the pin if PinToBottom is enabled.
func (*ScrollState) ScrollToView ¶
func (s *ScrollState) ScrollToView(y, height int)
ScrollToView ensures a region (y to y+height) is visible in the viewport. If the region is above the viewport, scrolls up to show it at the top. If the region is below the viewport, scrolls down to show it at the bottom. If the region is already visible, does nothing.
func (*ScrollState) ScrollUp ¶
func (s *ScrollState) ScrollUp(lines int) bool
ScrollUp scrolls up by the given number of lines. Returns true if scrolling was handled (callback handled it or offset changed). Returns false if already at the top and no callback handled it. If OnScrollUp is set and returns true, viewport scrolling is suppressed. If PinToBottom is enabled, scrolling up breaks the pin.
func (*ScrollState) SetOffset ¶
func (s *ScrollState) SetOffset(offset int)
SetOffset sets the scroll offset directly, clamping to valid bounds.
func (*ScrollState) SetOffsetX ¶
func (s *ScrollState) SetOffsetX(offset int)
SetOffsetX sets the horizontal scroll offset directly, clamping to valid bounds.
type Scrollable ¶
type Scrollable struct {
ID string // Optional unique identifier for the widget
Child Widget // The child widget to scroll
State *ScrollState // Required - holds scroll position
DisableScroll bool // If true, scrolling is disabled and scrollbar hidden (default: false)
Focusable bool // If true, widget can receive keyboard focus for scroll navigation
DisableFocus bool // If true, prevent keyboard focus
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling
Click func(MouseEvent) // Optional callback invoked when clicked
MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed
MouseUp func(MouseEvent) // Optional callback invoked when mouse is released
MouseMove func(MouseEvent) // Optional callback invoked when mouse is moved while dragging
Hover func(HoverEvent) // Optional callback invoked when hover state changes
// Scrollbar appearance customization
ScrollbarThumbColor Color // Custom thumb color (default: White unfocused, BrightCyan focused)
ScrollbarTrackColor Color // Custom track color (default: BrightBlack)
}
Scrollable is a container widget that enables vertical scrolling of its child when the child's content exceeds the available viewport height. A scrollbar is displayed on the right side when scrolling is active.
Example usage:
scrollState := terma.NewScrollState()
scrollable := terma.Scrollable{
State: scrollState,
Height: terma.Cells(10),
Child: myContent,
}
func (Scrollable) Build ¶
func (s Scrollable) Build(ctx BuildContext) Widget
Build returns itself as Scrollable manages its own child.
func (Scrollable) BuildLayoutNode ¶
func (s Scrollable) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this Scrollable widget. Implements the LayoutNodeBuilder interface.
func (Scrollable) GetContentDimensions ¶
func (s Scrollable) GetContentDimensions() (width, height Dimension)
GetContentDimensions returns the width and height dimension preferences.
func (Scrollable) GetStyle ¶
func (s Scrollable) GetStyle() Style
GetStyle returns the style of the scrollable widget. Implements the Styled interface.
func (Scrollable) IsFocusable ¶
func (s Scrollable) IsFocusable() bool
IsFocusable returns true if this widget can receive focus. Returns true if Focusable is set and scrolling is enabled. Note: We can't check canScroll() here because Layout hasn't run yet during focus collection.
func (Scrollable) OnClick ¶
func (s Scrollable) OnClick(event MouseEvent)
OnClick is called when the widget is clicked. Implements the Clickable interface.
func (Scrollable) OnHover ¶
func (s Scrollable) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions. Implements the Hoverable interface.
func (Scrollable) OnKey ¶
func (s Scrollable) OnKey(event KeyEvent) bool
OnKey handles key events when the widget is focused.
func (Scrollable) OnLayout ¶
func (s Scrollable) OnLayout(ctx BuildContext, metrics LayoutMetrics)
OnLayout caches layout metrics for scrollbar hit-testing and dragging.
func (Scrollable) OnMouseDown ¶
func (s Scrollable) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (Scrollable) OnMouseMove ¶
func (s Scrollable) OnMouseMove(event MouseEvent)
OnMouseMove is called when the mouse is moved while dragging. Implements the MouseMoveHandler interface.
func (Scrollable) OnMouseUp ¶
func (s Scrollable) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
func (Scrollable) Render ¶
func (s Scrollable) Render(ctx *RenderContext)
Render draws the scrollable widget and its child.
func (Scrollable) ScrollDown ¶
func (s Scrollable) ScrollDown(lines int) bool
ScrollDown scrolls the content down by the given number of lines. Returns true if scrolling was handled, false if scroll is disabled or at limit.
func (Scrollable) ScrollLeft ¶
func (s Scrollable) ScrollLeft(cols int) bool
ScrollLeft scrolls the content left by the given number of columns. Returns true if scrolling was handled, false if scroll is disabled or at limit.
func (Scrollable) ScrollRight ¶
func (s Scrollable) ScrollRight(cols int) bool
ScrollRight scrolls the content right by the given number of columns. Returns true if scrolling was handled, false if scroll is disabled or at limit.
func (Scrollable) ScrollUp ¶
func (s Scrollable) ScrollUp(lines int) bool
ScrollUp scrolls the content up by the given number of lines. Returns true if scrolling was handled, false if scroll is disabled or at limit.
func (Scrollable) WidgetID ¶
func (s Scrollable) WidgetID() string
WidgetID returns the widget's unique identifier. Implements the Identifiable interface.
type SerializedBuffer ¶
type SerializedBuffer struct {
Width int `json:"w"`
Height int `json:"h"`
Cells []SerializedCell `json:"cells"` // Row-major order
}
SerializedBuffer represents a buffer that can be JSON serialized.
func SerializeBuffer ¶
func SerializeBuffer(buf *uv.Buffer, width, height int) SerializedBuffer
SerializeBuffer converts a uv.Buffer to a serializable format.
func (*SerializedBuffer) ToBuffer ¶
func (sb *SerializedBuffer) ToBuffer() *uv.Buffer
ToBuffer converts a SerializedBuffer back to a uv.Buffer.
type SerializedCell ¶
type SerializedCell struct {
Content string `json:"c,omitempty"` // Cell content
Fg string `json:"f,omitempty"` // Foreground color as hex
Bg string `json:"b,omitempty"` // Background color as hex
Attrs uint8 `json:"a,omitempty"` // Style attributes
}
SerializedCell represents a cell that can be JSON serialized.
type Signal ¶
type Signal[T comparable] struct { // contains filtered or unexported fields }
Signal holds reactive state that automatically tracks dependencies. When the value changes, all subscribed widget nodes are marked dirty. Signal can be stored by value in structs; copies share the same underlying state.
func NewSignal ¶
func NewSignal[T comparable](initial T) Signal[T]
NewSignal creates a new signal with the given initial value.
func (Signal[T]) Get ¶
func (s Signal[T]) Get() T
Get returns the current value. If called during a widget's Build(), the widget is automatically subscribed to future changes. Thread-safe: can be called from any goroutine.
func (Signal[T]) IsValid ¶
IsValid returns true if the signal was properly initialized. An uninitialized Signal (zero value) returns false.
func (Signal[T]) Peek ¶
func (s Signal[T]) Peek() T
Peek returns the current value without subscribing. Thread-safe: can be called from any goroutine.
type Size ¶
type Size struct {
Width, Height int
}
Size represents the computed dimensions of a widget.
type SnapshotComparison ¶
type SnapshotComparison struct {
Name string // Test name / description
Description string // What should be visible in the snapshot (optional)
Expected string // SVG content or path
Actual string // SVG content or path
DiffSVG string // SVG highlighting differences (optional)
Passed bool // Whether they match
Stats SnapshotStats // Comparison statistics (optional)
}
SnapshotComparison represents a comparison between expected and actual snapshots.
type SnapshotStats ¶
type SnapshotStats struct {
TotalCells int // Total number of cells compared
MatchingCells int // Number of cells that match exactly
MismatchedCells int // Number of cells that differ
Similarity float64 // Percentage of matching cells (0-100)
}
SnapshotStats contains comparison statistics between two snapshots.
func CompareBuffers ¶
func CompareBuffers(expected, actual *uv.Buffer, width, height int) SnapshotStats
CompareBuffers compares two buffers and returns comparison statistics.
type SnapshotSuite ¶
type SnapshotSuite struct {
// contains filtered or unexported fields
}
SnapshotSuite provides a convenient way to run multiple snapshot assertions with custom options. Results are automatically collected into the global registry for the combined gallery.
Example:
func TestWidgets(t *testing.T) {
suite := terma.NewSnapshotSuite(t)
suite.Assert("button", buttonWidget, 20, 5)
suite.Assert("list", listWidget, 30, 10)
}
func NewSnapshotSuite ¶
func NewSnapshotSuite(t *testing.T) *SnapshotSuite
NewSnapshotSuite creates a new snapshot suite.
func (*SnapshotSuite) Assert ¶
func (s *SnapshotSuite) Assert(name string, widget Widget, width, height int, description ...string)
Assert renders a widget and compares against a golden file. Results are collected into the global registry for the combined gallery. An optional description can be provided to explain what should be visible in the snapshot.
func (*SnapshotSuite) WithOptions ¶
func (s *SnapshotSuite) WithOptions(opts SVGOptions) *SnapshotSuite
WithOptions sets custom SVG options for the suite.
type Spacer ¶
type Spacer struct {
Width Dimension // Defaults to Flex(1) if unset
Height Dimension // Defaults to Flex(1) if unset
MinWidth Dimension
MaxWidth Dimension
MinHeight Dimension
MaxHeight Dimension
}
Spacer is a non-visual widget that occupies space in layouts. It renders nothing but participates in layout calculations.
Common uses:
- Push widgets to opposite ends of a Row or Column
- Create flexible gaps that expand to fill available space
- Add fixed-size empty regions with Cells()
Default behavior: An unset dimension defaults to Flex(1), so a bare Spacer{} expands to fill available space in both directions.
Note: Explicitly setting Auto results in 0 size since Spacer has no content to fit. Use Flex(1) instead if you want the spacer to expand.
func (Spacer) Build ¶
func (s Spacer) Build(ctx BuildContext) Widget
Build returns itself as Spacer is a leaf widget.
func (Spacer) BuildLayoutNode ¶
func (s Spacer) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this Spacer widget.
func (Spacer) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences. If both dimensions are unset, both default to Flex(1) (bare Spacer{} expands in both directions). If one dimension is explicitly set to Flex/Percent, the other defaults to Auto (size 0), making Spacer{Width: Flex(1)} behave as a horizontal-only spacer.
func (Spacer) Render ¶
func (s Spacer) Render(ctx *RenderContext)
Render is a no-op for Spacer as it has no visual appearance.
type Span ¶
Span represents a segment of text with its own styling.
func HighlightSpans ¶
func HighlightSpans(text string, ranges []MatchRange, highlight SpanStyle) []Span
HighlightSpans builds spans with highlight style applied to matched ranges.
func ItalicSpan ¶
ItalicSpan creates an italic span with optional foreground color.
func ParseMarkup ¶
ParseMarkup parses a markup string and returns a slice of Spans. Supports styles like [bold], [italic], [underline] (or [b], [i], [u]), theme colors like [$Primary], background colors like [on $Surface], and literal hex colors like [#ff5500].
Examples:
ParseMarkup("Hello [bold]World[/]", theme)
ParseMarkup("Press [b $Accent]Enter[/] to continue", theme)
ParseMarkup("[bold $Error on $Background]Warning![/]", theme)
Style nesting is supported: [bold]Hello [italic]World[/][/] Use [[ to insert a literal [ character. Invalid markup is returned as literal text (graceful fallback).
func StrikethroughSpan ¶
StrikethroughSpan creates a strikethrough span with optional foreground color.
func StyledSpan ¶
StyledSpan creates a span with full style control.
func UnderlineSpan ¶
UnderlineSpan creates an underlined span with optional foreground color.
type SpanStyle ¶
type SpanStyle struct {
Foreground Color
Background Color
Bold bool
Faint bool
Italic bool
Underline UnderlineStyle
UnderlineColor Color
Blink bool
Reverse bool
Conceal bool
Strikethrough bool
}
SpanStyle defines text attributes for a span (colors + formatting).
func MatchHighlightStyle ¶
MatchHighlightStyle returns the standard SpanStyle used to highlight matched text in filtered lists, tables, trees, and similar widgets.
type Sparkline ¶
type Sparkline struct {
ID string // Optional unique identifier
Values []float64 // Data points to render
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // General styling (padding, margin, border)
// Bars allows customizing the character set from low to high.
// If empty or too short, the default sparkline bars are used.
Bars []string
// ColorByValue enables per-bar coloring based on normalized value.
// If ValueColorScale is unset, a theme-based gradient is used.
ColorByValue bool
ValueColorScale Gradient
// Optional scaling overrides. When set, these bounds are used instead of auto min/max.
MinValue *float64
MaxValue *float64
}
Sparkline renders a compact inline chart using Unicode bar characters.
Width defaults to the number of values, Height defaults to 1 cell. Set ColorByValue to vary bar colors by magnitude; ValueColorScale customizes the gradient.
func (Sparkline) Build ¶
func (s Sparkline) Build(ctx BuildContext) Widget
Build returns itself as Sparkline is a leaf widget.
func (Sparkline) BuildLayoutNode ¶
func (s Sparkline) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this Sparkline widget.
func (Sparkline) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences.
func (Sparkline) Layout ¶
func (s Sparkline) Layout(ctx BuildContext, constraints Constraints) Size
Layout computes the size of the sparkline.
func (Sparkline) Render ¶
func (s Sparkline) Render(ctx *RenderContext)
Render draws the sparkline to the render context.
type Spinner ¶
type Spinner struct {
ID string // Optional unique identifier
State *SpinnerState // Required - holds animation state
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling
}
Spinner displays an animated loading indicator. Use pure composition to add labels:
Row{Children: []Widget{
Spinner{State: spinnerState},
Text{Content: " Loading..."},
}}
func (Spinner) Build ¶
func (s Spinner) Build(ctx BuildContext) Widget
Build returns a Text widget showing the current frame.
func (Spinner) GetContentDimensions ¶
GetContentDimensions returns the dimensions.
type SpinnerState ¶
type SpinnerState struct {
// contains filtered or unexported fields
}
SpinnerState holds the animation state for a Spinner. Create with NewSpinnerState and pass to the Spinner widget.
func NewSpinnerState ¶
func NewSpinnerState(style SpinnerStyle) *SpinnerState
NewSpinnerState creates a new spinner state with the given style.
func (*SpinnerState) Frame ¶
func (s *SpinnerState) Frame() string
Frame returns the current animation frame. Call this in Build() to subscribe to animation updates and trigger rebuilds when the frame changes.
func (*SpinnerState) IsRunning ¶
func (s *SpinnerState) IsRunning() bool
IsRunning returns true if the spinner is currently animating.
type SpinnerStyle ¶
SpinnerStyle defines the visual appearance of a spinner.
type SplitPane ¶
type SplitPane struct {
// Required fields
ID string
State *SplitPaneState
First Widget
Second Widget
// Configuration
Orientation SplitPaneOrientation
DividerSize int
MinPaneSize int
DisableFocus bool
OnExitFocus func()
// Appearance
DividerForeground ColorProvider
DividerBackground ColorProvider
DividerFocusForeground ColorProvider
DividerFocusBackground ColorProvider
DividerChar string
// Standard widget fields
Width Dimension
Height Dimension
Style Style
Click func(MouseEvent)
MouseDown func(MouseEvent)
MouseUp func(MouseEvent)
MouseMove func(MouseEvent)
Hover func(HoverEvent) // Optional callback invoked when hover state changes
}
SplitPane divides space between two children with a draggable divider.
func (SplitPane) Build ¶
func (s SplitPane) Build(ctx BuildContext) Widget
Build returns itself as SplitPane manages its own children.
func (SplitPane) BuildLayoutNode ¶
func (s SplitPane) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this SplitPane widget.
func (SplitPane) ChildWidgets ¶
ChildWidgets returns the split pane's children for render tree construction.
func (SplitPane) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences.
func (SplitPane) IsFocusable ¶
IsFocusable returns true if this widget can receive focus.
func (SplitPane) OnClick ¶
func (s SplitPane) OnClick(event MouseEvent)
OnClick is called when the widget is clicked.
func (SplitPane) OnHover ¶
func (s SplitPane) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions.
func (SplitPane) OnLayout ¶
func (s SplitPane) OnLayout(ctx BuildContext, metrics LayoutMetrics)
OnLayout caches layout metrics for divider hit-testing and dragging.
func (SplitPane) OnMouseDown ¶
func (s SplitPane) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget.
func (SplitPane) OnMouseMove ¶
func (s SplitPane) OnMouseMove(event MouseEvent)
OnMouseMove is called when the mouse is moved while dragging.
func (SplitPane) OnMouseUp ¶
func (s SplitPane) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget.
func (SplitPane) Render ¶
func (s SplitPane) Render(ctx *RenderContext)
Render draws the divider for the split pane.
type SplitPaneOrientation ¶
type SplitPaneOrientation int
SplitPaneOrientation determines how the split divides space.
const ( // SplitHorizontal divides left/right. SplitHorizontal SplitPaneOrientation = iota // SplitVertical divides top/bottom. SplitVertical )
type SplitPaneState ¶
type SplitPaneState struct {
DividerPosition Signal[float64] // 0.0-1.0
// contains filtered or unexported fields
}
SplitPaneState holds the divider position for a SplitPane widget.
func NewSplitPaneState ¶
func NewSplitPaneState(initialPosition float64) *SplitPaneState
NewSplitPaneState creates a new SplitPaneState with the given initial position.
func (*SplitPaneState) GetPosition ¶
func (s *SplitPaneState) GetPosition() float64
GetPosition returns the current divider position without subscribing.
func (*SplitPaneState) SetPosition ¶
func (s *SplitPaneState) SetPosition(pos float64)
SetPosition sets the divider position (clamped to valid range).
type Stack ¶
type Stack struct {
ID string // Optional unique identifier for the widget
Children []Widget // Children to overlay (first at bottom, last on top)
Alignment Alignment // Default alignment for non-positioned children (default: top-start)
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling
Click func(MouseEvent) // Optional callback invoked when clicked
MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed
MouseUp func(MouseEvent) // Optional callback invoked when mouse is released
Hover func(HoverEvent) // Optional callback invoked when hover state changes
}
Stack overlays children on top of each other in z-order. First child is at the bottom, last child is on top.
Children can be:
- Regular widgets: positioned using the Stack's Alignment
- Positioned wrappers: positioned using edge offsets
Stack sizes itself based on the largest non-positioned child. Positioned children do not affect Stack's size.
func (Stack) AllChildren ¶
AllChildren returns all child widgets, unwrapping Positioned to get inner children. This is used by the render tree to match widgets with their computed layouts.
func (Stack) Build ¶
func (s Stack) Build(ctx BuildContext) Widget
Build returns itself as Stack manages its own children.
func (Stack) BuildLayoutNode ¶
func (s Stack) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode creates a StackNode for the layout system.
func (Stack) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences.
func (Stack) OnClick ¶
func (s Stack) OnClick(event MouseEvent)
OnClick is called when the widget is clicked.
func (Stack) OnHover ¶
func (s Stack) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions.
func (Stack) OnMouseDown ¶
func (s Stack) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (Stack) OnMouseUp ¶
func (s Stack) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
func (Stack) Render ¶
func (s Stack) Render(ctx *RenderContext)
Render is a no-op for Stack when using the RenderTree-based rendering path.
type Style ¶
type Style struct {
ForegroundColor ColorProvider // Can be Color or Gradient
BackgroundColor ColorProvider // Can be Color or Gradient
// Text attributes
Bold bool
Faint bool
Italic bool
Underline UnderlineStyle
UnderlineColor Color
Blink bool
Reverse bool
Conceal bool
Strikethrough bool
FillLine bool // Extend underline/strikethrough to fill the line width
// Layout
Padding EdgeInsets
Margin EdgeInsets
Border Border
// Dimensions (content-box)
Width Dimension
Height Dimension
MinWidth Dimension
MinHeight Dimension
MaxWidth Dimension
MaxHeight Dimension
}
Style defines the visual appearance of a widget.
func (Style) GetDimensions ¶
func (s Style) GetDimensions() DimensionSet
GetDimensions returns the style's dimension fields.
type Styled ¶
type Styled interface {
GetStyle() Style
}
Styled is implemented by widgets that have a Style. The framework uses this to extract padding and margin for automatic layout.
type Suggestion ¶
type Suggestion struct {
Label string // Display text in dropdown
Value string // Value to insert when selected
Description string // Optional secondary text (dimmed)
Icon string // Optional leading icon
Data any // User data for custom handling
}
Suggestion represents an autocomplete option.
type Switcher ¶
type Switcher struct {
// Active is the key of the currently visible child.
Active string
// Children maps string keys to widgets. Only the widget matching
// Active is rendered.
Children map[string]Widget
// Width specifies the width of the switcher container.
// Deprecated: use Style.Width.
Width Dimension
// Height specifies the height of the switcher container.
// Deprecated: use Style.Height.
Height Dimension
// Style applies styling to the switcher container.
Style Style
}
Switcher displays one child at a time based on a string key. Only the child matching the Active key is rendered; others are not built.
State preservation: Widget state lives in Signals and State objects (e.g., ListState, ScrollState) held by the App, not in widgets themselves. When switching between children, their state objects persist and the widget rebuilds with that state when reactivated.
Example:
Switcher{
Active: a.activeTab.Get(),
Children: map[string]Widget{
"home": HomeTab{listState: a.homeListState},
"settings": SettingsTab{},
"profile": ProfileTab{},
},
}
func (Switcher) Build ¶
func (s Switcher) Build(ctx BuildContext) Widget
Build returns itself since Switcher manages its own child rendering.
func (Switcher) BuildLayoutNode ¶
func (s Switcher) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this Switcher widget. Implements the LayoutNodeBuilder interface.
func (Switcher) GetContentDimensions ¶
GetContentDimensions returns the configured width and height.
type Tab ¶
type Tab struct {
Key string // Unique identifier (used for switching)
Label string // Display text (can differ from Key)
Content Widget // Optional - used by TabView, ignored by TabBar
}
Tab represents a single tab with its key, label, and optional content.
type TabBar ¶
type TabBar struct {
ID string // Optional unique identifier
DisableFocus bool // If true, prevent keyboard focus
State *TabState // Required - holds tabs and active key
KeybindPattern TabKeybindPattern // Position keybind style
OnTabChange func(key string) // Tab selection callback
OnTabClose func(key string) // Close button callback
Closable bool // Show close buttons
AllowReorder bool // Enable ctrl+left/right reordering
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Container style
TabStyle Style // Inactive tab style
ActiveTabStyle Style // Active tab style
Click func(MouseEvent) // Optional callback invoked when clicked
MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed
MouseUp func(MouseEvent) // Optional callback invoked when mouse is released
Hover func(HoverEvent) // Optional callback invoked when hover state changes
}
TabBar is a focusable widget that renders a horizontal row of tabs. It supports keyboard navigation and position-based keybindings.
func (TabBar) Build ¶
func (t TabBar) Build(ctx BuildContext) Widget
Build renders the tab bar as a Row of styled text widgets.
func (TabBar) GetDimensions ¶
GetDimensions returns the width and height dimension preferences.
func (TabBar) IsFocusable ¶
IsFocusable returns true to allow keyboard navigation.
func (TabBar) OnClick ¶
func (t TabBar) OnClick(event MouseEvent)
OnClick is called when the widget is clicked.
func (TabBar) OnHover ¶
func (t TabBar) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions.
func (TabBar) OnMouseDown ¶
func (t TabBar) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed.
func (TabBar) OnMouseUp ¶
func (t TabBar) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released.
type TabKeybindPattern ¶
type TabKeybindPattern int
TabKeybindPattern specifies the style of position-based keybindings.
const ( // TabKeybindNone disables position-based keybindings. TabKeybindNone TabKeybindPattern = iota // TabKeybindNumbers uses 1, 2, 3... 9 for tab switching. TabKeybindNumbers // TabKeybindAltNumbers uses alt+1, alt+2... alt+9 for tab switching. TabKeybindAltNumbers // TabKeybindCtrlNumbers uses ctrl+1, ctrl+2... ctrl+9 for tab switching. TabKeybindCtrlNumbers )
type TabState ¶
type TabState struct {
// contains filtered or unexported fields
}
TabState holds the state for a TabBar or TabView widget. It is the source of truth for tabs and the active tab, and must be provided to TabBar/TabView.
func NewTabState ¶
NewTabState creates a new TabState with the given tabs. The first tab becomes active by default.
func NewTabStateWithActive ¶
NewTabStateWithActive creates a new TabState with the given tabs and active tab key.
func (*TabState) ActiveIndex ¶
ActiveIndex returns the index of the currently active tab, or -1 if not found.
func (*TabState) ActiveKey ¶
ActiveKey returns the key of the currently active tab (subscribes to changes).
func (*TabState) ActiveKeyPeek ¶
ActiveKeyPeek returns the key of the currently active tab without subscribing.
func (*TabState) EditingKey ¶
EditingKey returns the key of the tab being edited (subscribes to changes).
func (*TabState) MoveTabLeft ¶
MoveTabLeft moves the tab with the given key one position to the left. Returns true if the move was successful.
func (*TabState) MoveTabRight ¶
MoveTabRight moves the tab with the given key one position to the right. Returns true if the move was successful.
func (*TabState) RemoveTab ¶
RemoveTab removes a tab by key. Returns true if the tab was found and removed.
func (*TabState) SelectIndex ¶
SelectIndex sets the active tab by index.
func (*TabState) SelectNext ¶
func (s *TabState) SelectNext()
SelectNext moves to the next tab, wrapping to the first if at the end.
func (*TabState) SelectPrevious ¶
func (s *TabState) SelectPrevious()
SelectPrevious moves to the previous tab, wrapping to the last if at the beginning.
func (*TabState) SetActiveKey ¶
SetActiveKey sets the active tab by key.
func (*TabState) StartEditing ¶
StartEditing begins editing mode for a tab's label.
type TabView ¶
type TabView struct {
ID string // Optional identifier
State *TabState // Required - holds tabs and active key
KeybindPattern TabKeybindPattern // Position keybind style
OnTabChange func(key string) // Tab selection callback
OnTabClose func(key string) // Close button callback
Closable bool // Show close buttons
AllowReorder bool // Enable ctrl+left/right reordering
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Container style
TabBarStyle Style // Style for the tab bar row
TabStyle Style // Inactive tab style
ActiveTabStyle Style // Active tab style
ContentStyle Style // Style for the content area
}
TabView is a convenience composite that combines TabBar with a content area. It renders tabs at the top and the active tab's content below.
func (TabView) Build ¶
func (t TabView) Build(ctx BuildContext) Widget
Build renders the tab view as a Column with TabBar and content area.
func (TabView) GetDimensions ¶
GetDimensions returns the width and height dimension preferences.
type Table ¶
type Table[T any] struct { ID string // Optional unique identifier DisableFocus bool // If true, prevent keyboard focus CursorStyle // Embedded - CursorPrefix/SelectedPrefix fields for customizable indicators State *TableState[T] // Required - holds rows and cursor position Columns []TableColumn // Required - defines column count and widths RenderCell func(row T, rowIndex int, colIndex int, active bool, selected bool) Widget // Cell renderer (default uses fmt) RenderCellWithMatch func(row T, rowIndex int, colIndex int, active bool, selected bool, match MatchResult) Widget // Optional cell renderer with match data Filter *FilterState // Optional filter state for matching rows MatchCell func(row T, rowIndex int, colIndex int, query string, options FilterOptions) MatchResult // Optional matcher per cell RenderHeader func(colIndex int) Widget // Optional header renderer (takes precedence over column headers) OnSelect func(row T) // Callback invoked when Enter is pressed on a row OnCursorChange func(row T) // Callback invoked when cursor moves to a different row ScrollState *ScrollState // Optional state for scroll-into-view RowHeight int // Optional uniform row height override (default 0 = layout metrics / fallback 1) ColumnSpacing int // Space between columns RowSpacing int // Space between rows SelectionMode TableSelectionMode // Cursor/selection highlight mode (row/column/cursor) MultiSelect bool // Enable multi-select mode (shift+move to extend) Width Dimension // Deprecated: use Style.Width Height Dimension // Deprecated: use Style.Height Style Style // Optional styling Click func(MouseEvent) // Optional callback invoked when clicked MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed MouseUp func(MouseEvent) // Optional callback invoked when mouse is released Hover func(HoverEvent) // Optional callback invoked when hover state changes }
Table is a generic focusable widget that displays a navigable table of rows. Use with Scrollable and a shared ScrollState to enable scroll-into-view.
func (Table[T]) Build ¶
func (t Table[T]) Build(ctx BuildContext) Widget
Build returns a table container that arranges the rendered cells.
func (Table[T]) CursorRow ¶
func (t Table[T]) CursorRow() T
CursorRow returns the row at the current cursor position. Returns the zero value of T if the table is empty or state is nil.
func (Table[T]) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences. Implements the Dimensioned interface.
func (Table[T]) GetStyle ¶
GetStyle returns the style of the table widget. Implements the Styled interface.
func (Table[T]) IsFocusable ¶
IsFocusable returns true to allow keyboard navigation. Implements the Focusable interface.
func (Table[T]) OnClick ¶
func (t Table[T]) OnClick(event MouseEvent)
OnClick is called when the widget is clicked. Implements the Clickable interface.
func (Table[T]) OnHover ¶
func (t Table[T]) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions. Implements the Hoverable interface.
func (Table[T]) OnKey ¶
OnKey handles keys not covered by declarative keybindings. Implements the Focusable interface.
func (Table[T]) OnMouseDown ¶
func (t Table[T]) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (Table[T]) OnMouseUp ¶
func (t Table[T]) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
type TableColumn ¶
type TableColumn struct {
Width Dimension // Optional width (Cells, Percent, Flex, Auto)
Header Widget // Optional header widget for this column
}
TableColumn defines layout properties for a table column.
type TableSelectionMode ¶
type TableSelectionMode int
TableSelectionMode controls how cursor and selection highlights are applied.
const ( // TableSelectionCursor highlights only the cursor cell (default). TableSelectionCursor TableSelectionMode = iota // TableSelectionRow highlights the entire row. TableSelectionRow // TableSelectionColumn highlights the entire column. TableSelectionColumn )
type TableState ¶
type TableState[T any] struct { Rows AnySignal[[]T] // Reactive table rows CursorIndex Signal[int] // Cursor position (row index) CursorColumn Signal[int] // Cursor position (column index) Selection AnySignal[map[int]struct{}] // Selected indices (row/column/cell based on selection mode) // contains filtered or unexported fields }
TableState holds the state for a Table widget. It is the source of truth for rows and cursor position, and must be provided to Table. Rows is a reactive Signal - changes trigger automatic re-renders.
func NewTableState ¶
func NewTableState[T any](initialRows []T) *TableState[T]
NewTableState creates a new TableState with the given initial rows.
func (*TableState[T]) Append ¶
func (s *TableState[T]) Append(row T)
Append adds a row to the end of the table.
func (*TableState[T]) Clear ¶
func (s *TableState[T]) Clear()
Clear removes all rows from the table.
func (*TableState[T]) ClearAnchor ¶
func (s *TableState[T]) ClearAnchor()
ClearAnchor removes the anchor point.
func (*TableState[T]) ClearSelection ¶
func (s *TableState[T]) ClearSelection()
ClearSelection removes all rows from the selection.
func (*TableState[T]) Deselect ¶
func (s *TableState[T]) Deselect(index int)
Deselect removes the row at the given index from the selection.
func (*TableState[T]) GetAnchor ¶
func (s *TableState[T]) GetAnchor() int
GetAnchor returns the anchor index, or -1 if no anchor is set.
func (*TableState[T]) GetRows ¶
func (s *TableState[T]) GetRows() []T
GetRows returns the current table rows (without subscribing to changes).
func (*TableState[T]) HasAnchor ¶
func (s *TableState[T]) HasAnchor() bool
HasAnchor returns true if an anchor point is set.
func (*TableState[T]) InsertAt ¶
func (s *TableState[T]) InsertAt(index int, row T)
InsertAt inserts a row at the specified index. If index is out of bounds, it's clamped to valid range.
func (*TableState[T]) IsSelected ¶
func (s *TableState[T]) IsSelected(index int) bool
IsSelected returns true if the row at the given index is selected.
func (*TableState[T]) Prepend ¶
func (s *TableState[T]) Prepend(row T)
Prepend adds a row to the beginning of the table.
func (*TableState[T]) RemoveAt ¶
func (s *TableState[T]) RemoveAt(index int) bool
RemoveAt removes the row at the specified index. Returns true if a row was removed, false if index was out of bounds.
func (*TableState[T]) RemoveWhere ¶
func (s *TableState[T]) RemoveWhere(predicate func(T) bool) int
RemoveWhere removes all rows matching the predicate. Returns the number of rows removed.
func (*TableState[T]) RowCount ¶
func (s *TableState[T]) RowCount() int
RowCount returns the number of rows.
func (*TableState[T]) Select ¶
func (s *TableState[T]) Select(index int)
Select adds the row at the given index to the selection.
func (*TableState[T]) SelectAll ¶
func (s *TableState[T]) SelectAll()
SelectAll selects all rows in the table.
func (*TableState[T]) SelectColumn ¶
func (s *TableState[T]) SelectColumn(index int)
SelectColumn sets cursor to a specific column index.
func (*TableState[T]) SelectFirst ¶
func (s *TableState[T]) SelectFirst()
SelectFirst moves cursor to the first row.
func (*TableState[T]) SelectIndex ¶
func (s *TableState[T]) SelectIndex(index int)
SelectIndex sets cursor to a specific index, clamped to valid range.
func (*TableState[T]) SelectLast ¶
func (s *TableState[T]) SelectLast()
SelectLast moves cursor to the last row.
func (*TableState[T]) SelectNext ¶
func (s *TableState[T]) SelectNext()
SelectNext moves cursor to the next row.
func (*TableState[T]) SelectPrevious ¶
func (s *TableState[T]) SelectPrevious()
SelectPrevious moves cursor to the previous row.
func (*TableState[T]) SelectRange ¶
func (s *TableState[T]) SelectRange(from, to int)
SelectRange selects all rows between from and to (inclusive).
func (*TableState[T]) SelectedIndices ¶
func (s *TableState[T]) SelectedIndices() []int
SelectedIndices returns the indices of all selected rows in ascending order. Note: This assumes row-based selection.
func (*TableState[T]) SelectedRow ¶
func (s *TableState[T]) SelectedRow() (T, bool)
SelectedRow returns the currently selected row (if any).
func (*TableState[T]) SelectedRows ¶
func (s *TableState[T]) SelectedRows() []T
SelectedRows returns all currently selected rows. Note: This assumes row-based selection.
func (*TableState[T]) SetAnchor ¶
func (s *TableState[T]) SetAnchor(index int)
SetAnchor sets the anchor point for shift-selection.
func (*TableState[T]) SetRows ¶
func (s *TableState[T]) SetRows(rows []T)
SetRows replaces all rows and clamps cursor to valid range.
func (*TableState[T]) ToggleSelection ¶
func (s *TableState[T]) ToggleSelection(index int)
ToggleSelection toggles the selection state of the row at the given index.
type Text ¶
type Text struct {
ID string // Optional unique identifier for the widget
Content string // Plain text (used if Spans is empty)
Spans []Span // Rich text segments (takes precedence if non-empty)
Wrap WrapMode // Wrapping mode (default = WrapNone)
TextAlign TextAlign // Horizontal alignment (default = TextAlignLeft)
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling (colors, inherited by spans)
Click func(MouseEvent) // Optional callback invoked when clicked
MouseDown func(MouseEvent) // Optional callback invoked when mouse is pressed
MouseUp func(MouseEvent) // Optional callback invoked when mouse is released
Hover func(HoverEvent) // Optional callback invoked when hover state changes
}
Text is a leaf widget that displays text content.
func Label ¶
func Label(content string, variant LabelVariant, theme ThemeData) Text
Label returns a styled Text widget with the given variant colors. Applies padding x=1, y=0 and variant-appropriate foreground/background.
func ParseMarkupToText ¶
ParseMarkupToText parses a markup string and returns a Text widget. This is a convenience wrapper around ParseMarkup.
Example:
ParseMarkupToText("Press [b $Warning]Tab[/] to switch focus", theme)
func (Text) Build ¶
func (t Text) Build(ctx BuildContext) Widget
Build returns itself as Text is a leaf widget.
func (Text) BuildLayoutNode ¶
func (t Text) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this Text widget. Implements the LayoutNodeBuilder interface.
func (Text) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences.
func (Text) OnClick ¶
func (t Text) OnClick(event MouseEvent)
OnClick is called when the widget is clicked. Implements the Clickable interface.
func (Text) OnHover ¶
func (t Text) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions. Implements the Hoverable interface.
func (Text) OnMouseDown ¶
func (t Text) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (Text) OnMouseUp ¶
func (t Text) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
func (Text) Render ¶
func (t Text) Render(ctx *RenderContext)
Render draws the text to the render context.
type TextAlign ¶
type TextAlign int
TextAlign defines horizontal alignment for text content within available width.
type TextArea ¶
type TextArea struct {
ID string // Optional unique identifier
DisableFocus bool // If true, prevent keyboard focus
State *TextAreaState // Required - holds text and cursor position
Placeholder string // Text shown when empty and unfocused
Highlighter Highlighter // Optional: dynamic text highlighting
LineHighlights []LineHighlight // Optional: line-based background highlights
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height
Style Style // Optional styling
RequireInsertMode bool // If true, require entering insert mode to edit
ScrollState *ScrollState // Optional state for scroll-into-view
OnChange func(text string) // Callback when text changes
OnSubmit func(text string) // Callback when submit key is pressed
Click func(MouseEvent) // Optional click callback
MouseDown func(MouseEvent) // Optional mouse down callback
MouseUp func(MouseEvent) // Optional mouse up callback
Hover func(HoverEvent) // Optional hover callback
Blur func() // Optional blur callback
ExtraKeybinds []Keybind // Optional additional keybinds (checked before defaults)
}
TextArea is a multi-line focusable text entry widget.
func (TextArea) Build ¶
func (t TextArea) Build(ctx BuildContext) Widget
Build returns self since TextArea is a leaf widget with custom rendering.
func (TextArea) BuildLayoutNode ¶
func (t TextArea) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this TextArea widget. Implements the LayoutNodeBuilder interface so Scrollable can measure it.
func (TextArea) CapturesKey ¶
CapturesKey returns true if this key would be captured by the text area (i.e., typed as text rather than bubbling to ancestors). This is true for printable characters without modifiers when in insert mode.
func (TextArea) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences.
func (TextArea) IsFocusable ¶
IsFocusable returns true, indicating this widget can receive keyboard focus.
func (TextArea) Keybinds ¶
Keybinds returns the declarative keybindings for this text area. ExtraKeybinds are checked first, allowing custom behavior to override defaults.
func (TextArea) Layout ¶
func (t TextArea) Layout(ctx BuildContext, constraints Constraints) Size
Layout computes the size of the text area.
func (TextArea) OnClick ¶
func (t TextArea) OnClick(event MouseEvent)
OnClick is called when the widget is clicked.
func (TextArea) OnHover ¶
func (t TextArea) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions.
func (TextArea) OnMouseDown ¶
func (t TextArea) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (TextArea) OnMouseMove ¶
func (t TextArea) OnMouseMove(event MouseEvent)
OnMouseMove is called when the mouse is moved while dragging. Implements the MouseMoveHandler interface.
func (TextArea) OnMouseUp ¶
func (t TextArea) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
func (TextArea) Render ¶
func (t TextArea) Render(ctx *RenderContext)
Render draws the text area with cursor.
type TextAreaState ¶
type TextAreaState struct {
Content AnySignal[[]string] // Grapheme clusters for Unicode safety
CursorIndex Signal[int] // Grapheme index (0 = before first char)
InsertMode Signal[bool] // True when edits are allowed
WrapMode Signal[WrapMode] // WrapNone or WrapSoft/WrapHard
SelectionAnchor Signal[int] // -1 = no selection, else anchor grapheme index
ReadOnly Signal[bool] // When true, content cannot be edited but cursor can move
// contains filtered or unexported fields
}
TextAreaState holds the state for a TextArea widget. It is the source of truth for text content, cursor position, wrapping mode, and insert mode.
func NewTextAreaState ¶
func NewTextAreaState(initial string) *TextAreaState
NewTextAreaState creates a new TextAreaState with optional initial text.
func (*TextAreaState) ClearSelection ¶
func (s *TextAreaState) ClearSelection()
ClearSelection clears the selection anchor.
func (*TextAreaState) CursorDown ¶
func (s *TextAreaState) CursorDown()
CursorDown moves the cursor down by one display line.
func (*TextAreaState) CursorDownBy ¶
func (s *TextAreaState) CursorDownBy(lines int)
CursorDownBy moves the cursor down by the given number of display lines.
func (*TextAreaState) CursorEnd ¶
func (s *TextAreaState) CursorEnd()
CursorEnd moves the cursor to the end of the current line.
func (*TextAreaState) CursorHome ¶
func (s *TextAreaState) CursorHome()
CursorHome moves the cursor to the start of the current line.
func (*TextAreaState) CursorLeft ¶
func (s *TextAreaState) CursorLeft()
CursorLeft moves the cursor left by one grapheme.
func (*TextAreaState) CursorRight ¶
func (s *TextAreaState) CursorRight()
CursorRight moves the cursor right by one grapheme.
func (*TextAreaState) CursorScreenPosition ¶
func (s *TextAreaState) CursorScreenPosition(widgetX, widgetY int) (screenX, screenY int)
CursorScreenPosition returns the screen offset of the cursor relative to the widget's top-left corner. Used for positioning popups (like autocomplete) at the cursor location.
func (*TextAreaState) CursorUp ¶
func (s *TextAreaState) CursorUp()
CursorUp moves the cursor up by one display line.
func (*TextAreaState) CursorUpBy ¶
func (s *TextAreaState) CursorUpBy(lines int)
CursorUpBy moves the cursor up by the given number of display lines.
func (*TextAreaState) CursorWordLeft ¶
func (s *TextAreaState) CursorWordLeft()
CursorWordLeft moves the cursor to the previous word boundary.
func (*TextAreaState) CursorWordRight ¶
func (s *TextAreaState) CursorWordRight()
CursorWordRight moves the cursor to the next word boundary.
func (*TextAreaState) DeleteBackward ¶
func (s *TextAreaState) DeleteBackward()
DeleteBackward deletes the grapheme before the cursor.
func (*TextAreaState) DeleteForward ¶
func (s *TextAreaState) DeleteForward()
DeleteForward deletes the grapheme at the cursor.
func (*TextAreaState) DeleteSelection ¶
func (s *TextAreaState) DeleteSelection() bool
DeleteSelection deletes the selected text. Returns true if selection was deleted, false if there was no selection.
func (*TextAreaState) DeleteToBeginning ¶
func (s *TextAreaState) DeleteToBeginning()
DeleteToBeginning deletes from cursor to beginning of line.
func (*TextAreaState) DeleteToEnd ¶
func (s *TextAreaState) DeleteToEnd()
DeleteToEnd deletes from cursor to end of line.
func (*TextAreaState) DeleteWordBackward ¶
func (s *TextAreaState) DeleteWordBackward()
DeleteWordBackward deletes the word before the cursor.
func (*TextAreaState) GetSelectedText ¶
func (s *TextAreaState) GetSelectedText() string
GetSelectedText returns the selected text as a string. Returns empty string if there is no selection.
func (*TextAreaState) GetSelectionBounds ¶
func (s *TextAreaState) GetSelectionBounds() (start, end int)
GetSelectionBounds returns the normalized selection bounds (start, end). Returns (-1, -1) if there is no selection.
func (*TextAreaState) GetText ¶
func (s *TextAreaState) GetText() string
GetText returns the content as a string.
func (*TextAreaState) HasSelection ¶
func (s *TextAreaState) HasSelection() bool
HasSelection returns true if there is an active selection.
func (*TextAreaState) Insert ¶
func (s *TextAreaState) Insert(text string)
Insert inserts text at the cursor position and advances the cursor.
func (*TextAreaState) InsertNewline ¶
func (s *TextAreaState) InsertNewline()
InsertNewline inserts a newline at the cursor position.
func (*TextAreaState) ReplaceSelection ¶
func (s *TextAreaState) ReplaceSelection(text string)
ReplaceSelection deletes any selected text and inserts the given text.
func (*TextAreaState) SelectAll ¶
func (s *TextAreaState) SelectAll()
SelectAll selects all text (anchor=0, cursor=len).
func (*TextAreaState) SelectLine ¶
func (s *TextAreaState) SelectLine(index int)
SelectLine selects the line at the given grapheme index.
func (*TextAreaState) SelectWord ¶
func (s *TextAreaState) SelectWord(index int)
SelectWord selects the word at the given grapheme index.
func (*TextAreaState) SetCursorFromLocalPosition ¶
func (s *TextAreaState) SetCursorFromLocalPosition(localX, localY int, contentWidth int)
SetCursorFromLocalPosition moves the cursor to the given local position within the widget. It accounts for scroll offset internally. contentWidth is the width available for text content (excluding scrollbar space).
func (*TextAreaState) SetSelectionAnchor ¶
func (s *TextAreaState) SetSelectionAnchor(index int)
SetSelectionAnchor sets the selection anchor to the given index.
func (*TextAreaState) SetText ¶
func (s *TextAreaState) SetText(text string)
SetText replaces the content and clamps the cursor.
func (*TextAreaState) ToggleWrap ¶
func (s *TextAreaState) ToggleWrap()
ToggleWrap toggles between WrapNone and WrapSoft.
type TextHighlight ¶
type TextHighlight struct {
Start int // Grapheme index (inclusive)
End int // Grapheme index (exclusive)
Style SpanStyle // Style to apply
}
TextHighlight represents a styled region of text by grapheme index.
type TextInput ¶
type TextInput struct {
ID string // Optional unique identifier
DisableFocus bool // If true, prevent keyboard focus
State *TextInputState // Required - holds text and cursor position
Placeholder string // Text shown when empty and unfocused
Highlighter Highlighter // Optional: dynamic text highlighting
Width Dimension // Deprecated: use Style.Width
Height Dimension // Deprecated: use Style.Height (ignored; content height is always 1)
Style Style // Optional styling (padding adds to outer size automatically)
OnChange func(text string) // Callback when text changes
OnSubmit func(text string) // Callback when Enter pressed
Click func(MouseEvent) // Optional click callback
MouseDown func(MouseEvent) // Optional mouse down callback
MouseUp func(MouseEvent) // Optional mouse up callback
Hover func(HoverEvent) // Optional hover callback
Blur func() // Optional blur callback
ExtraKeybinds []Keybind // Optional additional keybinds (checked before defaults)
}
TextInput is a single-line focusable text entry widget. Content height is always 1 cell (single line). Use Style.Padding to add visual space around the text - the framework automatically accounts for padding.
func (TextInput) Build ¶
func (t TextInput) Build(ctx BuildContext) Widget
Build returns self since TextInput is a leaf widget with custom rendering.
func (TextInput) BuildLayoutNode ¶
func (t TextInput) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode builds a layout node for this TextInput widget. Implements the LayoutNodeBuilder interface.
func (TextInput) CapturesKey ¶
CapturesKey returns true if this key would be captured by the text input (i.e., typed as text rather than bubbling to ancestors). This is true for printable characters without modifiers when not read-only.
func (TextInput) CursorScreenPosition ¶
CursorScreenPosition returns the screen X position of the cursor given the widget's screen X position. Used for IME positioning.
func (TextInput) GetContentDimensions ¶
GetContentDimensions returns the content-box dimensions. Height is always 1 cell (single line of text). Padding/border from Style are automatically added by the framework to compute the final outer size.
func (TextInput) IsFocusable ¶
IsFocusable returns true, indicating this widget can receive keyboard focus.
func (TextInput) Keybinds ¶
Keybinds returns the declarative keybindings for this text input. ExtraKeybinds are checked first, allowing custom behavior to override defaults.
func (TextInput) Layout ¶
func (t TextInput) Layout(ctx BuildContext, constraints Constraints) Size
Layout computes the size of the text input.
func (TextInput) OnClick ¶
func (t TextInput) OnClick(event MouseEvent)
OnClick is called when the widget is clicked.
func (TextInput) OnHover ¶
func (t TextInput) OnHover(event HoverEvent)
OnHover is called on hover enter/leave transitions.
func (TextInput) OnMouseDown ¶
func (t TextInput) OnMouseDown(event MouseEvent)
OnMouseDown is called when the mouse is pressed on the widget. Implements the MouseDownHandler interface.
func (TextInput) OnMouseMove ¶
func (t TextInput) OnMouseMove(event MouseEvent)
OnMouseMove is called when the mouse is moved while dragging. Implements the MouseMoveHandler interface.
func (TextInput) OnMouseUp ¶
func (t TextInput) OnMouseUp(event MouseEvent)
OnMouseUp is called when the mouse is released on the widget. Implements the MouseUpHandler interface.
func (TextInput) Render ¶
func (t TextInput) Render(ctx *RenderContext)
Render draws the text input with cursor.
type TextInputState ¶
type TextInputState struct {
Content AnySignal[[]string] // Grapheme clusters for Unicode safety
CursorIndex Signal[int] // Grapheme index (0 = before first char)
SelectionAnchor Signal[int] // -1 = no selection, else anchor grapheme index
ReadOnly Signal[bool] // When true, content cannot be edited but cursor can move
// contains filtered or unexported fields
}
TextInputState holds the state for a TextInput widget. It is the source of truth for text content and cursor position, and must be provided to TextInput.
func NewTextInputState ¶
func NewTextInputState(initial string) *TextInputState
NewTextInputState creates a new TextInputState with optional initial text.
func (*TextInputState) ClearSelection ¶
func (s *TextInputState) ClearSelection()
ClearSelection clears the selection anchor.
func (*TextInputState) CursorEnd ¶
func (s *TextInputState) CursorEnd()
CursorEnd moves the cursor to the end.
func (*TextInputState) CursorHome ¶
func (s *TextInputState) CursorHome()
CursorHome moves the cursor to the beginning.
func (*TextInputState) CursorLeft ¶
func (s *TextInputState) CursorLeft()
CursorLeft moves the cursor left by one grapheme.
func (*TextInputState) CursorRight ¶
func (s *TextInputState) CursorRight()
CursorRight moves the cursor right by one grapheme.
func (*TextInputState) CursorWordLeft ¶
func (s *TextInputState) CursorWordLeft()
CursorWordLeft moves the cursor to the previous word boundary.
func (*TextInputState) CursorWordRight ¶
func (s *TextInputState) CursorWordRight()
CursorWordRight moves the cursor to the next word boundary.
func (*TextInputState) DeleteBackward ¶
func (s *TextInputState) DeleteBackward()
DeleteBackward deletes the grapheme before the cursor.
func (*TextInputState) DeleteForward ¶
func (s *TextInputState) DeleteForward()
DeleteForward deletes the grapheme at the cursor.
func (*TextInputState) DeleteSelection ¶
func (s *TextInputState) DeleteSelection() bool
DeleteSelection deletes the selected text. Returns true if selection was deleted, false if there was no selection.
func (*TextInputState) DeleteToBeginning ¶
func (s *TextInputState) DeleteToBeginning()
DeleteToBeginning deletes from cursor to beginning of line.
func (*TextInputState) DeleteToEnd ¶
func (s *TextInputState) DeleteToEnd()
DeleteToEnd deletes from cursor to end of line.
func (*TextInputState) DeleteWordBackward ¶
func (s *TextInputState) DeleteWordBackward()
DeleteWordBackward deletes the word before the cursor.
func (*TextInputState) GetSelectedText ¶
func (s *TextInputState) GetSelectedText() string
GetSelectedText returns the selected text as a string. Returns empty string if there is no selection.
func (*TextInputState) GetSelectionBounds ¶
func (s *TextInputState) GetSelectionBounds() (start, end int)
GetSelectionBounds returns the normalized selection bounds (start, end). Returns (-1, -1) if there is no selection.
func (*TextInputState) GetText ¶
func (s *TextInputState) GetText() string
GetText returns the content as a string.
func (*TextInputState) HasSelection ¶
func (s *TextInputState) HasSelection() bool
HasSelection returns true if there is an active selection.
func (*TextInputState) Insert ¶
func (s *TextInputState) Insert(text string)
Insert inserts text at the cursor position and advances the cursor.
func (*TextInputState) ReplaceSelection ¶
func (s *TextInputState) ReplaceSelection(text string)
ReplaceSelection deletes any selected text and inserts the given text.
func (*TextInputState) SelectAll ¶
func (s *TextInputState) SelectAll()
SelectAll selects all text (anchor=0, cursor=len).
func (*TextInputState) SelectWord ¶
func (s *TextInputState) SelectWord(index int)
SelectWord selects the word at the given grapheme index.
func (*TextInputState) SetCursorFromLocalPosition ¶
func (s *TextInputState) SetCursorFromLocalPosition(localX int)
SetCursorFromLocalPosition moves the cursor to the given local X position. It accounts for scroll offset internally. This mirrors TextArea's method but is simplified for single-line input.
func (*TextInputState) SetSelectionAnchor ¶
func (s *TextInputState) SetSelectionAnchor(index int)
SetSelectionAnchor sets the selection anchor to the given index.
func (*TextInputState) SetText ¶
func (s *TextInputState) SetText(text string)
SetText replaces the content and clamps the cursor.
type ThemeData ¶
type ThemeData struct {
Name string
IsLight bool // True for light themes, false for dark themes
// Core branding colors
Primary Color
Secondary Color
Accent Color
// Surface colors (backgrounds)
Background Color
Surface Color
SurfaceHover Color
Surface2 Color // Level 2 (nested elements)
Surface3 Color // Level 3 (deeply nested)
// Text colors
Text Color
TextMuted Color
TextOnPrimary Color
TextOnSecondary Color
TextOnAccent Color
TextDisabled Color // Disabled state text
// Border colors
Border Color
FocusRing Color
// Feedback colors
Error Color
Warning Color
Success Color
Info Color
// Feedback text variants
TextOnError Color
TextOnWarning Color
TextOnSuccess Color
TextOnInfo Color
// ActiveCursor colors
ActiveCursor Color // Active selection background (cursor/focused item)
Selection Color // Dimmer selection background (multi-select without focus)
SelectionText Color // Text on selection
// Scrollbar colors
ScrollbarTrack Color
ScrollbarThumb Color
// Overlay/modal
Overlay Color // Semi-transparent backdrop
// Input-specific
Placeholder Color // Placeholder text
Cursor Color // Text cursor/caret
// Link
Link Color // Clickable text links
// Label text colors (variant colors blended toward readable text)
PrimaryText Color
SecondaryText Color
AccentText Color
SuccessText Color
ErrorText Color
WarningText Color
InfoText Color
// Label background colors (variant colors faded/dimmed)
PrimaryBg Color
SecondaryBg Color
AccentBg Color
SuccessBg Color
ErrorBg Color
WarningBg Color
InfoBg Color
}
ThemeData holds all semantic colors for a theme. This is the data structure users provide when registering custom themes.
func ExtendTheme ¶
func ExtendTheme(baseName string, opts ...ThemeOption) ThemeData
ExtendTheme creates a new theme based on an existing one with modifications. Returns zero ThemeData if base theme not found.
type ThemeOption ¶
type ThemeOption func(*ThemeData)
ThemeOption is a functional option for modifying theme data.
func WithActiveCursor ¶
func WithActiveCursor(c Color) ThemeOption
WithActiveCursor sets the ActiveCursor color.
func WithBackground ¶
func WithBackground(c Color) ThemeOption
WithBackground sets the Background color.
func WithFocusRing ¶
func WithFocusRing(c Color) ThemeOption
WithFocusRing sets the FocusRing color.
func WithPlaceholder ¶
func WithPlaceholder(c Color) ThemeOption
WithPlaceholder sets the Placeholder color.
func WithScrollbarThumb ¶
func WithScrollbarThumb(c Color) ThemeOption
WithScrollbarThumb sets the ScrollbarThumb color.
func WithScrollbarTrack ¶
func WithScrollbarTrack(c Color) ThemeOption
WithScrollbarTrack sets the ScrollbarTrack color.
func WithSecondary ¶
func WithSecondary(c Color) ThemeOption
WithSecondary sets the Secondary color.
func WithSelection ¶
func WithSelection(c Color) ThemeOption
WithSelection sets the Selection color.
func WithSelectionText ¶
func WithSelectionText(c Color) ThemeOption
WithSelectionText sets the SelectionText color.
func WithSurfaceHover ¶
func WithSurfaceHover(c Color) ThemeOption
WithSurfaceHover sets the SurfaceHover color.
func WithTextDisabled ¶
func WithTextDisabled(c Color) ThemeOption
WithTextDisabled sets the TextDisabled color.
func WithTextMuted ¶
func WithTextMuted(c Color) ThemeOption
WithTextMuted sets the TextMuted color.
func WithTextOnAccent ¶
func WithTextOnAccent(c Color) ThemeOption
WithTextOnAccent sets the TextOnAccent color.
func WithTextOnError ¶
func WithTextOnError(c Color) ThemeOption
WithTextOnError sets the TextOnError color.
func WithTextOnInfo ¶
func WithTextOnInfo(c Color) ThemeOption
WithTextOnInfo sets the TextOnInfo color.
func WithTextOnPrimary ¶
func WithTextOnPrimary(c Color) ThemeOption
WithTextOnPrimary sets the TextOnPrimary color.
func WithTextOnSecondary ¶
func WithTextOnSecondary(c Color) ThemeOption
WithTextOnSecondary sets the TextOnSecondary color.
func WithTextOnSuccess ¶
func WithTextOnSuccess(c Color) ThemeOption
WithTextOnSuccess sets the TextOnSuccess color.
func WithTextOnWarning ¶
func WithTextOnWarning(c Color) ThemeOption
WithTextOnWarning sets the TextOnWarning color.
type Tooltip ¶
type Tooltip struct {
// ID optionally identifies this tooltip for anchor positioning.
// If not provided, an auto-generated ID is used.
ID string
// Content is the plain text to display in the tooltip.
// Used if Spans is empty.
Content string
// Spans is the rich text to display in the tooltip.
// Takes precedence over Content if non-empty.
Spans []Span
// Child is the widget that triggers the tooltip.
Child Widget
// Position specifies where the tooltip appears relative to the child.
// Default: TooltipTop
Position TooltipPosition
// Offset is the gap in cells between the child and the tooltip.
// Default: 0 (no gap)
Offset int
// Style overrides the default tooltip styling.
Style Style
}
Tooltip displays contextual help when hovering over or focusing on an element. It wraps a child widget and shows a floating tooltip based on the configured trigger.
Example - simple hover tooltip:
Tooltip{
ID: "submit-tooltip",
Content: "Submit the form",
Child: Button{ID: "submit", Label: "Submit"},
}
Example - positioned tooltip with focus trigger:
Tooltip{
ID: "password-tooltip",
Content: "3-20 characters",
Position: TooltipRight,
Child: TextInput{ID: "password", State: passState},
}
Example - rich text tooltip:
Tooltip{
ID: "save-tooltip",
Spans: ParseMarkup("[b]Ctrl+S[/] to save", ctx.Theme()),
Position: TooltipBottom,
Child: SaveIcon{},
}
func (Tooltip) Build ¶
func (t Tooltip) Build(ctx BuildContext) Widget
Build constructs the tooltip widget tree.
func (Tooltip) BuildLayoutNode ¶
func (t Tooltip) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
BuildLayoutNode wraps the child in a container for layout.
func (Tooltip) ChildWidgets ¶
ChildWidgets returns the wrapped child for render tree building.
type TooltipPosition ¶
type TooltipPosition int
TooltipPosition specifies where the tooltip appears relative to the child.
const ( // TooltipTop positions the tooltip above the child (default). TooltipTop TooltipPosition = iota // TooltipBottom positions the tooltip below the child. TooltipBottom // TooltipLeft positions the tooltip to the left of the child. TooltipLeft // TooltipRight positions the tooltip to the right of the child. TooltipRight )
type Tree ¶
type Tree[T any] struct { ID string DisableFocus bool State *TreeState[T] NodeID func(data T) string RenderNode func(node T, ctx TreeNodeContext) Widget RenderNodeWithMatch func(node T, ctx TreeNodeContext, match MatchResult) Widget HasChildren func(node T) bool OnExpand func(node T, path []int, setChildren func([]TreeNode[T])) Filter *FilterState MatchNode func(node T, query string, options FilterOptions) MatchResult OnSelect func(node T, selected []T) OnCursorChange func(node T) ScrollState *ScrollState Width Dimension // Deprecated: use Style.Width Height Dimension // Deprecated: use Style.Height Style Style MultiSelect bool CursorStyle // Embedded - CursorPrefix/SelectedPrefix for optional indicators Indent int ShowGuideLines *bool GuideStyle Style ExpandIndicator string CollapseIndicator string LeafIndicator string }
Tree is a generic focusable widget that displays a navigable tree.
func (Tree[T]) Build ¶
func (t Tree[T]) Build(ctx BuildContext) Widget
Build builds the tree into a column of rendered nodes.
func (Tree[T]) GetDimensions ¶
GetDimensions returns the width and height dimension preferences.
func (Tree[T]) IsFocusable ¶
IsFocusable returns true to allow keyboard navigation.
func (Tree[T]) OnMouseDown ¶
func (t Tree[T]) OnMouseDown(event MouseEvent)
OnMouseDown moves the cursor to the clicked node.
type TreeNode ¶
TreeNode represents a node in a tree. Children == nil means not loaded (lazy), Children == [] means leaf.
type TreeNodeContext ¶
type TreeNodeContext struct {
Path []int // Path to this node
Depth int // Nesting level (0 = root)
Expanded bool // Is this node currently expanded?
Expandable bool // Can this node be expanded?
Active bool // Is cursor on this node?
Selected bool // Is this node selected?
FilteredAncestor bool // Visible due to descendant match
}
TreeNodeContext contains rendering metadata for a node.
type TreeState ¶
type TreeState[T any] struct { Nodes AnySignal[[]TreeNode[T]] // Root nodes CursorPath AnySignal[[]int] // Path to cursor, e.g. [0, 2, 1] Collapsed AnySignal[map[string]bool] // Collapsed node identifiers Selection AnySignal[map[string]struct{}] // Selected node identifiers // contains filtered or unexported fields }
TreeState holds state for a Tree widget.
func NewDirectoryTreeState ¶
func NewDirectoryTreeState(root string) *TreeState[DirectoryEntry]
NewDirectoryTreeState creates a TreeState for a single root path.
func NewDirectoryTreeStateWithRoots ¶
func NewDirectoryTreeStateWithRoots(roots []string) *TreeState[DirectoryEntry]
NewDirectoryTreeStateWithRoots creates a TreeState for multiple root paths.
func NewTreeState ¶
NewTreeState creates a new TreeState with the given root nodes.
func (*TreeState[T]) ClearSelection ¶
func (s *TreeState[T]) ClearSelection()
ClearSelection clears all selected nodes.
func (*TreeState[T]) CollapseAll ¶
func (s *TreeState[T]) CollapseAll()
CollapseAll collapses all nodes in the tree.
func (*TreeState[T]) CursorDown ¶
func (s *TreeState[T]) CursorDown()
CursorDown moves the cursor to the next visible node.
func (*TreeState[T]) CursorNode ¶
CursorNode returns the data at the cursor position.
func (*TreeState[T]) CursorToFirstChild ¶
func (s *TreeState[T]) CursorToFirstChild()
CursorToFirstChild moves the cursor to the first child if it is visible.
func (*TreeState[T]) CursorToParent ¶
func (s *TreeState[T]) CursorToParent()
CursorToParent moves the cursor to its parent if possible.
func (*TreeState[T]) CursorUp ¶
func (s *TreeState[T]) CursorUp()
CursorUp moves the cursor to the previous visible node.
func (*TreeState[T]) ExpandAll ¶
func (s *TreeState[T]) ExpandAll()
ExpandAll clears all collapsed state.
func (*TreeState[T]) IsCollapsed ¶
IsCollapsed returns true if the node at the given path is collapsed.
func (*TreeState[T]) IsSelected ¶
IsSelected returns true if the node at the given path is selected.
func (*TreeState[T]) NodeAtPath ¶
NodeAtPath returns the node at the given path.
func (*TreeState[T]) SelectedPaths ¶
SelectedPaths returns all selected node paths in pre-order.
func (*TreeState[T]) SetChildren ¶
SetChildren sets the children for the node at the given path.
func (*TreeState[T]) ToggleSelection ¶
ToggleSelection toggles selection for the node at the given path.
type UnderlineStyle ¶
type UnderlineStyle int
UnderlineStyle defines the visual style of underlined text.
const ( UnderlineNone UnderlineStyle = iota UnderlineSingle UnderlineDouble UnderlineCurly UnderlineDotted UnderlineDashed )
Underline style constants.
type VerticalAlignment ¶
type VerticalAlignment int
VerticalAlignment specifies vertical positioning within available space.
const ( // VAlignTop aligns content at the top of the available space. VAlignTop VerticalAlignment = iota // VAlignCenter centers content vertically. VAlignCenter // VAlignBottom aligns content at the bottom of the available space. VAlignBottom )
type Widget ¶
type Widget interface {
Build(ctx BuildContext) Widget
}
Widget is the base interface for all UI elements. Leaf widgets (like Text) return themselves from Build(). Container widgets return a composed widget tree.
func DisabledWhen ¶
DisabledWhen disables all focusable widgets in the subtree when condition is true. Disabled widgets cannot receive keyboard focus and should render with disabled styling. The child is still rendered and takes up space in layout.
Example:
DisabledWhen(!form.IsValid(), Button{Label: "Submit", OnPress: submit})
func EnabledWhen ¶
EnabledWhen is the inverse of DisabledWhen. When condition is true, the child is rendered normally. When condition is false, the child is disabled.
Example:
EnabledWhen(form.IsValid(), Button{Label: "Submit", OnPress: submit})
func HideWhen ¶
HideWhen is the inverse of ShowWhen. When condition is true, returns EmptyWidget (hidden). When condition is false, returns the child widget.
Example:
HideWhen(isLoading.Get(), Content{})
func Inert ¶
Inert prevents all focusable widgets in the subtree from receiving keyboard focus. Unlike DisabledWhen, the child renders normally with no visual changes. Use this for display-only instances of interactive widgets (e.g., a Table used for layout inside another Table's cell).
Example:
Inert(Table[T]{State: previewState, ...})
func InvisibleWhen ¶
InvisibleWhen is the inverse of VisibleWhen. When condition is true, space is reserved but child is not rendered. When condition is false, child is rendered normally.
Example:
InvisibleWhen(isSecret, SensitiveData{}) // space held but content hidden
func ShowWhen ¶
ShowWhen conditionally renders a child widget. When condition is true, returns the child widget normally. When condition is false, returns EmptyWidget (no space, no render).
Example:
ShowWhen(user.IsAdmin(), AdminPanel{})
ShowWhen(items.Len() > 0, ItemList{})
func VisibleWhen ¶
VisibleWhen reserves space for a child regardless of visibility. When condition is true, the child is rendered normally. When condition is false, space is reserved but nothing is rendered and the widget does not receive focus or hover events.
This is similar to CSS `visibility: hidden` - the element is invisible but still affects layout.
Example:
VisibleWhen(hasData.Get(), Chart{}) // reserves chart space even when no data
type WidgetEntry ¶
WidgetEntry stores a widget along with its position and identity.
type WidgetRegistry ¶
type WidgetRegistry struct {
// contains filtered or unexported fields
}
WidgetRegistry tracks all widgets and their positions during render. Widgets are recorded in render order (depth-first), so later entries are "on top" visually and should receive events first.
func NewWidgetRegistry ¶
func NewWidgetRegistry() *WidgetRegistry
NewWidgetRegistry creates a new widget registry.
func (*WidgetRegistry) Entries ¶
func (r *WidgetRegistry) Entries() []WidgetEntry
Entries returns all recorded widget entries.
func (*WidgetRegistry) FocusableAt ¶
func (r *WidgetRegistry) FocusableAt(x, y int) *WidgetEntry
FocusableAt returns the innermost focusable widget containing the point (x, y). Returns nil if no focusable widget contains the point. Since widgets are recorded in render order (parents before children), we search back-to-front to find the innermost focusable.
func (*WidgetRegistry) IncrementTotal ¶
func (r *WidgetRegistry) IncrementTotal()
IncrementTotal increments the total widget count (including non-visible widgets).
func (*WidgetRegistry) Record ¶
func (r *WidgetRegistry) Record(widget Widget, eventWidget Widget, id string, bounds Rect)
Record adds a widget to the registry with its bounds and optional ID.
func (*WidgetRegistry) Reset ¶
func (r *WidgetRegistry) Reset()
Reset clears all entries for a new render pass.
func (*WidgetRegistry) ScrollableAt ¶
func (r *WidgetRegistry) ScrollableAt(x, y int) *Scrollable
ScrollableAt returns the innermost Scrollable widget containing the point (x, y). Returns nil if no Scrollable contains the point. Since widgets are recorded in render order (parents before children), we search back-to-front to find the innermost scrollable.
func (*WidgetRegistry) ScrollablesAt ¶
func (r *WidgetRegistry) ScrollablesAt(x, y int) []*Scrollable
ScrollablesAt returns all Scrollable widgets containing the point (x, y), ordered from innermost to outermost. Since widgets are recorded in render order (parents before children), we search back-to-front and collect all matching scrollables.
func (*WidgetRegistry) TotalCount ¶
func (r *WidgetRegistry) TotalCount() int
TotalCount returns the total number of widgets rendered, including those scrolled out of view that aren't in the entries list.
func (*WidgetRegistry) WidgetAt ¶
func (r *WidgetRegistry) WidgetAt(x, y int) *WidgetEntry
WidgetAt returns the topmost widget containing the point (x, y). Returns nil if no widget contains the point. Since widgets are recorded in render order, we search back-to-front to find the topmost (last rendered) widget at this position.
func (*WidgetRegistry) WidgetByID ¶
func (r *WidgetRegistry) WidgetByID(id string) *WidgetEntry
WidgetByID returns the widget entry with the given ID. Returns nil if no widget has that ID.
Source Files
¶
- alignment.go
- animated_value.go
- animation.go
- animation_controller.go
- app.go
- autocomplete.go
- bool_ptr.go
- breadcrumbs.go
- button.go
- checkbox.go
- color.go
- command_palette.go
- conditional.go
- context.go
- dialog.go
- dimension.go
- directory_tree.go
- dock.go
- easing.go
- filter.go
- floating.go
- focus.go
- focus_trap.go
- frame_animation.go
- highlight.go
- hover.go
- keybind.go
- keybindbar.go
- keyformat.go
- label.go
- layout.go
- layout_helpers.go
- layout_metrics.go
- list.go
- log.go
- markup.go
- menu.go
- panic.go
- print.go
- progressbar.go
- registry.go
- render.go
- render_tree.go
- scroll.go
- signal.go
- snapshot.go
- snapshot_assert.go
- spacer.go
- sparkline.go
- spinner.go
- split_pane.go
- stack.go
- style.go
- switcher.go
- tab.go
- table.go
- table_layout.go
- text.go
- text_area.go
- text_input.go
- theme.go
- tooltip.go
- tree.go
- widget.go