Documentation
¶
Overview ¶
Coordinate table from Kitty gen/rowcolumn-diacritics.txt (Unicode 6.0). https://sw.kovidgoyal.net/kitty/graphics-protocol/#unicode-placeholders
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 CursorBlink() bool
- func DarkThemeNames() []string
- func Dispatch(fn func())
- 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 NerdFontSymbol(symbol, fallback string) string
- func NerdFontsEnabled() bool
- func OpenURL(rawURL string) error
- func Print(widget Widget) error
- func PrintAbove(w Widget)
- func PrintAboveText(text string)
- 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 ReadClipboard(selection ClipboardSelection, fn func(content string))
- 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) error
- func RunExternal(cmd *exec.Cmd) error
- func RunInline(root Widget, opts InlineOptions) 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 Select[T, R comparable](s Signal[T], fn func(T) R) R
- func SelectAny[T any, R comparable](s AnySignal[T], fn func(T) R) R
- func SetClipboard(selection ClipboardSelection, content string)
- func SetClipboardMethod(m ClipboardMethod)
- func SetCursorBlink(enabled bool)
- func SetCursorBlinkStyle(style CursorBlinkStyle)
- func SetCursorPulseConfig(config CursorPulseConfig)
- func SetDebugLogging(enabled bool)
- func SetNerdFontsEnabled(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 ThemeDisplayName(name string) string
- func ThemeNames() []string
- func WriteTerminal(seq 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 OuterBorder(color ColorProvider, decorations ...BorderDecoration) Border
- func RoundedBorder(color ColorProvider, decorations ...BorderDecoration) Border
- func SquareBorder(color ColorProvider, decorations ...BorderDecoration) Border
- func TallBorder(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) PendingChord() []string
- 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 ClipboardMethod
- type ClipboardSelection
- 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) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
- 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) OnMouseWheel(event MouseEvent) bool
- 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 ContainerLayoutBuilder
- type CrossAxisAlign
- type CursorBlinkStyle
- type CursorProvider
- type CursorPulseConfig
- type CursorStyle
- type DecorationPosition
- type Dialog
- type Dimension
- type DimensionSet
- type Dimensioned
- type DirectoryEntry
- type DirectoryTree
- func (d DirectoryTree) Build(ctx BuildContext) Widget
- func (d DirectoryTree) IsFocusable() bool
- func (d DirectoryTree) Keybinds() []Keybind
- func (d DirectoryTree) OnKey(event KeyEvent) bool
- func (d DirectoryTree) OnMouseDown(event MouseEvent)
- func (d DirectoryTree) OnMouseMove(event MouseEvent)
- func (d DirectoryTree) OnMouseUp(event MouseEvent)
- func (d DirectoryTree) WidgetID() string
- type Dock
- func (d Dock) AllChildren() []Widget
- func (d Dock) Build(ctx BuildContext) Widget
- func (d Dock) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
- 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 Draggable
- type DropTarget
- type EasingFunc
- type Edge
- type EdgeInsets
- type EmptyWidget
- type Field
- type FieldBinding
- type FieldState
- func NewFieldState[T comparable](inputID string, binding FieldBinding[T], validators ...Validator[T]) *FieldState
- func NewTextAreaField(inputID string, input *TextAreaState, validators ...Validator[string]) *FieldState
- func NewTextInputField(inputID string, input *TextInputState, validators ...Validator[string]) *FieldState
- func (s *FieldState) Accept()
- func (s *FieldState) Dirty() bool
- func (s *FieldState) Enabled() bool
- func (s *FieldState) Errors() []string
- func (s *FieldState) InputID() string
- func (s *FieldState) Reset()
- func (s *FieldState) SetEnabled(enabled bool)
- func (s *FieldState) Touch()
- func (s *FieldState) Touched() bool
- func (s *FieldState) Valid() bool
- func (s *FieldState) Validate() bool
- type FileFilter
- type FilePicker
- func (p FilePicker) Build(ctx BuildContext) Widget
- func (p FilePicker) Cancel()
- func (p FilePicker) GetContentDimensions() (Dimension, Dimension)
- func (p FilePicker) GetStyle() Style
- func (p FilePicker) Keybinds() []Keybind
- func (p FilePicker) OnKey(KeyEvent) bool
- func (p FilePicker) Submit() bool
- func (p FilePicker) WidgetID() string
- type FilePickerEntry
- type FilePickerFileSystem
- type FilePickerMode
- type FilePickerState
- type FilterMode
- type FilterOptions
- type FilterState
- type FilteredView
- type FloatCollector
- type FloatConfig
- type FloatEntry
- type FloatGeometry
- type FloatPosition
- type FloatShadow
- type Floating
- type FocusCollector
- func (fc *FocusCollector) Collect(widget Widget, autoID string, ctx BuildContext)
- func (fc *FocusCollector) CollectGlobalKeybinds(widget Widget, 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) HandlePaste(text string) 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 Form
- type FormState
- 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 HoverEventSource
- type HoverEventType
- type Hoverable
- type Identifiable
- type Image
- type ImageFit
- type ImageResource
- type InlineExit
- type InlineOptions
- type InsertStrategy
- type Interpolator
- type IntrinsicContentSizer
- type JSONNode
- type JSONViewer
- type JSONViewerState
- type JumpState
- type JumpTarget
- type Jumpable
- type Jumper
- 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]) OnMouseMove(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 Markdown
- type MarkdownState
- type MatchRange
- type MatchResult
- type Menu
- type MenuItem
- type MenuState
- type MouseDownHandler
- type MouseEvent
- type MouseMoveHandler
- type MouseUpHandler
- type MouseWheelHandler
- type Offset
- type Panic
- type PasteHandler
- type Pilot
- func (p *Pilot) Advance(d time.Duration)
- func (p *Pilot) AssertSnapshot(name string, description ...string)
- func (p *Pilot) Bounds(id string) (Rect, bool)
- func (p *Pilot) Buffer() *uv.Buffer
- func (p *Pilot) Click(id string)
- func (p *Pilot) ClickAt(x, y int)
- func (p *Pilot) Clipboard() string
- func (p *Pilot) Exited() bool
- func (p *Pilot) FocusedID() string
- func (p *Pilot) Hover(id string)
- func (p *Pilot) Keybinds() []Keybind
- func (p *Pilot) MouseDown(x, y int, button uv.MouseButton, mod uv.KeyMod)
- func (p *Pilot) MouseMove(x, y int)
- func (p *Pilot) MouseUp(x, y int, button uv.MouseButton, mod uv.KeyMod)
- func (p *Pilot) Now() time.Time
- func (p *Pilot) Paste(text string)
- func (p *Pilot) PointerShape() PointerShape
- func (p *Pilot) Press(keys ...string)
- func (p *Pilot) Resize(width, height int)
- func (p *Pilot) ScreenText() string
- func (p *Pilot) Scroll(x, y, lines int)
- func (p *Pilot) Send(events ...uv.Event)
- func (p *Pilot) TextOf(id string) string
- func (p *Pilot) Type(text string)
- func (p *Pilot) WaitUntil(cond func() bool, timeout time.Duration)
- type PointerShape
- type Positioned
- type PresentedText
- func AnySignalMarkup[T any](signal AnySignal[T], format func(T) string) PresentedText
- func AnySignalText[T any](signal AnySignal[T], format func(T) string) PresentedText
- func ComputedSpans(layoutText string, compute func(theme ThemeData) []Span) PresentedText
- func ComputedText(layoutText string, compute func() string) PresentedText
- func PresentHighlightedText(layoutText string, layoutStyle Style, currentStyle func() Style, ...) PresentedText
- func PresentPrefixedText(layoutText, content string, layoutStyle Style, currentStyle func() Style, ...) PresentedText
- func PresentStyledText(layoutText string, layoutStyle Style, currentStyle func() Style, ...) PresentedText
- func PresentText(layoutText string, layoutStyle Style, currentStyle func() Style, ...) PresentedText
- func SignalMarkup[T comparable](signal Signal[T], format func(T) string) PresentedText
- func SignalText[T comparable](signal Signal[T], format func(T) string) PresentedText
- func (t PresentedText) Build(ctx BuildContext) Widget
- func (t PresentedText) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (t PresentedText) ContentHeightHint(width int) int
- func (t PresentedText) ContentWidthHint() int
- func (t PresentedText) GetContentDimensions() (width, height Dimension)
- func (t PresentedText) GetStyle() Style
- func (t PresentedText) Render(ctx *RenderContext)
- type PresentedTextPaint
- 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) DrawCells(x, y int, cells []uv.Cell)
- func (ctx *RenderContext) DrawImage(x, y, width, height int, source *ImageResource, fit ImageFit)
- 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) IsFocusedID(id string) 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 RenderStats
- 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) PointerOwnerAt(x, y int) *WidgetEntry
- 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) Stats() RenderStats
- func (r *Renderer) TopFloat() *FloatEntry
- func (r *Renderer) Update(root Widget) []FocusableEntry
- func (r *Renderer) WidgetAt(x, y int) *WidgetEntry
- func (r *Renderer) WidgetByID(id string) *WidgetEntry
- type ResizableCellBuffer
- type Row
- func (r Row) Build(ctx BuildContext) Widget
- func (r Row) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
- 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) OnMouseWheel(event MouseEvent) bool
- 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) PageDown() bool
- func (s *ScrollState) PageUp() 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) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
- 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) OnMouseWheel(event MouseEvent) bool
- 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 SelectBox
- func (s SelectBox[T]) Build(ctx BuildContext) Widget
- func (s SelectBox[T]) CapturesKey(key string) bool
- func (s SelectBox[T]) GetContentDimensions() (Dimension, Dimension)
- func (s SelectBox[T]) IsFocusable() bool
- func (s SelectBox[T]) Keybinds() []Keybind
- func (s SelectBox[T]) OnBlur()
- func (s SelectBox[T]) OnClick(event MouseEvent)
- func (s SelectBox[T]) OnKey(event KeyEvent) bool
- func (s SelectBox[T]) WidgetID() string
- type SelectOption
- type SelectState
- type SerializedBuffer
- type SerializedCell
- type Shimmer
- type ShimmerPath
- type ShimmerState
- 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 LinkSpan(text, url 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
- func (s Spinner) Build(ctx BuildContext) Widget
- func (s Spinner) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (s Spinner) ContentHeightHint(width int) int
- func (s Spinner) ContentWidthHint() int
- func (s Spinner) GetContentDimensions() (width, height Dimension)
- func (s Spinner) GetStyle() Style
- func (s Spinner) Render(ctx *RenderContext)
- func (s Spinner) WidgetID() string
- type SpinnerState
- type SpinnerStyle
- type SplitPane
- func (s SplitPane) Build(ctx BuildContext) Widget
- func (s SplitPane) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
- 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) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
- 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) OnMouseWheel(event MouseEvent) bool
- func (s Stack) Render(ctx *RenderContext)
- func (s Stack) WidgetID() string
- type Style
- type Styled
- type Suggestion
- type Switcher
- func (s Switcher) Build(ctx BuildContext) Widget
- func (s Switcher) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
- func (s Switcher) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (s Switcher) GetContentDimensions() (Dimension, Dimension)
- func (s Switcher) GetStyle() Style
- 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) OnMouseWheel(event MouseEvent) bool
- func (t TabBar) TabID(key string) string
- 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) MoveTab(key string, index int) 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]) OnMouseMove(event MouseEvent)
- func (t Table[T]) OnMouseUp(event MouseEvent)
- func (t Table[T]) OnMouseWheel(event MouseEvent) bool
- func (t Table[T]) WidgetID() string
- type TableColumn
- type TableSelectionMode
- type TableSort
- type TableSortDirection
- 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 Task
- type TaskPhase
- 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) OnMouseWheel(event MouseEvent) bool
- 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) ContentHeightHint(width int) int
- func (t TextArea) ContentWidthHint() int
- func (t TextArea) CursorPosition() (x, y int, visible bool)
- func (t TextArea) GetContentDimensions() (width, height Dimension)
- func (t TextArea) GetStyle() Style
- func (t TextArea) HandlePaste(text string) bool
- 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) OnLayout(ctx BuildContext, metrics LayoutMetrics)
- 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 TextAreaEdit
- type TextAreaState
- func (s *TextAreaState) CanRedo() bool
- func (s *TextAreaState) CanUndo() bool
- func (s *TextAreaState) ClearHistory()
- func (s *TextAreaState) ClearSearch()
- 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) NextMatch()
- func (s *TextAreaState) PreviousMatch()
- func (s *TextAreaState) Redo() bool
- func (s *TextAreaState) ReplaceSelection(text string)
- func (s *TextAreaState) ReplaceText(text string, cursor int)
- func (s *TextAreaState) SearchMatches() []TextRange
- func (s *TextAreaState) SearchPosition() (current, total int)
- 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) SetSearch(query string)
- func (s *TextAreaState) SetSelectionAnchor(index int)
- func (s *TextAreaState) SetText(text string)
- func (s *TextAreaState) ToggleWrap()
- func (s *TextAreaState) Undo() bool
- 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) ContentHeightHint(width int) int
- func (t TextInput) ContentWidthHint() int
- func (t TextInput) CursorPosition() (x, y int, visible bool)
- func (t TextInput) CursorScreenPosition(widgetX int) int
- func (t TextInput) GetContentDimensions() (width, height Dimension)
- func (t TextInput) GetStyle() Style
- func (t TextInput) HandlePaste(text string) bool
- 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) CanRedo() bool
- func (s *TextInputState) CanUndo() bool
- func (s *TextInputState) ClearHistory()
- 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) Redo() bool
- func (s *TextInputState) ReplaceSelection(text string)
- func (s *TextInputState) ReplaceText(text string, cursor int)
- 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)
- func (s *TextInputState) Undo() bool
- type TextRange
- 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 WithHover(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 Toast
- type ToastID
- type ToastOptions
- type ToastSeverity
- type ToastState
- func (s *ToastState) Clear()
- func (s *ToastState) Dismiss(id ToastID)
- func (s *ToastState) Error(message string) ToastID
- func (s *ToastState) Info(message string) ToastID
- func (s *ToastState) Len() int
- func (s *ToastState) Notify(toast Toast) ToastID
- func (s *ToastState) Success(message string) ToastID
- func (s *ToastState) Warning(message string) ToastID
- type Toasts
- type Tooltip
- func (t Tooltip) Build(ctx BuildContext) Widget
- func (t Tooltip) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
- func (t Tooltip) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
- func (t Tooltip) ChildWidgets() []Widget
- func (t Tooltip) WidgetID() string
- 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]) OnMouseMove(event MouseEvent)
- func (t Tree[T]) OnMouseUp(event MouseEvent)
- func (t Tree[T]) WidgetID() string
- type TreeNode
- type TreeNodeContext
- type TreeState
- func (s *TreeState[T]) ClearAnchor()
- 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 Validator
- 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 ThemeSwatch(name string) 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, visible 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" ThemeNameMoonstone = "moonstone" ThemeNameBonsai = "bonsai" ThemeNameGarnet = "garnet" ThemeNameKintsugi = "kintsugi" ThemeNameAmethyst = "amethyst" ThemeNameLantern = "lantern" // 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 ( DirtyNone dirtyLevel = iota DirtyPaint DirtyLayout DirtyBuild )
const DefaultHoverAlpha = 0.08
DefaultHoverAlpha is the opacity of the Text color that a theme's Hover defaults to.
const DefaultJumpHints = "asdfghjklqwertyuiopzxcvbnm"
DefaultJumpHints are the characters dynamic jump hints are made from when Jumper.Hints is unset: the home row first, then the rows above and below.
const DefaultJumpKey = "ctrl+o"
DefaultJumpKey is the key that toggles jump mode when Jumper.Key is unset.
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 DefaultRedoKeys = []string{"ctrl+y"}
DefaultRedoKeys redo the last undone edit in a TextInput or TextArea whose RedoKeys is nil. ctrl+shift+z is left out: terminals without the kitty keyboard protocol send it as ctrl+z, so it would undo instead.
var DefaultUndoKeys = []string{"ctrl+z"}
DefaultUndoKeys undo the last edit in a TextInput or TextArea whose UndoKeys is nil.
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 CursorBlink ¶ added in v0.16.0
func CursorBlink() bool
CursorBlink reports whether the text cursor blinks. See SetCursorBlink.
func DarkThemeNames ¶
func DarkThemeNames() []string
DarkThemeNames returns a slice of all registered dark theme names in alphabetical order.
func Dispatch ¶ added in v0.5.0
func Dispatch(fn func())
Dispatch schedules fn to run on the app/event-loop goroutine before the next rendered frame. During a headless Renderer render, fn runs after the frame finishes, and the renderer draws again before returning. Outside an app or a headless render, fn runs immediately. Between Quit and Run returning, fn is dropped: no frame will show its effects, and running it on the caller's goroutine would race the app's last frame.
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. The letter keeps its case: ^D means ctrl with an uppercase D (ctrl+D or ctrl+shift+d). Chords join their key presses with spaces.
Examples:
- "ctrl+c" → "^c"
- "ctrl+shift+x" → "^X"
- "shift+tab" → "Shift+Tab"
- "enter" → "Enter"
- " " → "Space"
- "ctrl+x ctrl+s" → "^x ^s"
func FormatKeyEmacs ¶
FormatKeyEmacs formats keys in Emacs style. ctrl → C-, alt/meta → M-, shift → S-. Chords join their key presses with spaces.
Examples:
- "ctrl+x" → "C-x"
- "alt+x" → "M-x"
- "ctrl+alt+x" → "C-M-x"
- "shift+tab" → "S-TAB"
- "enter" → "RET"
- " " → "SPC"
- "ctrl+x ctrl+s" → "C-x C-s"
func FormatKeyVerbose ¶
FormatKeyVerbose formats keys in readable title case. Named keys are capitalised; a character key keeps its case, so "d" and "D" stay distinct. Chords join their key presses with spaces.
Examples:
- "ctrl+x" → "Ctrl+x"
- "ctrl+X" → "Ctrl+X"
- "shift+tab" → "Shift+Tab"
- "enter" → "Enter"
- " " → "Space"
- "ctrl+k ctrl+s" → "Ctrl+k Ctrl+s"
func FormatKeyVim ¶
FormatKeyVim formats keys in Vim style. Named and modified keys are wrapped in angle brackets with modifier prefixes. Chords are written as one sequence, as Vim does.
Examples:
- "ctrl+x" → "<C-x>"
- "alt+x" → "<M-x>"
- "shift+tab" → "<S-Tab>"
- "enter" → "<CR>"
- " " → "<Space>"
- "g g" → "gg"
- "ctrl+w v" → "<C-w>v"
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 NerdFontSymbol ¶ added in v0.26.0
NerdFontSymbol returns symbol when NerdFontsEnabled is true, or fallback otherwise. Both strings are returned unchanged, so they may include padding, multiple characters, or be empty. The result can be used anywhere a string is accepted.
The choice is made on each call. Call from Build to update the widget when SetNerdFontsEnabled changes the preference, including layout when the two strings have different widths. A string resolved during setup stays unchanged.
Example:
Text{Content: NerdFontSymbol("\uf07b", "[dir]") + " Projects"}
func NerdFontsEnabled ¶ added in v0.26.0
func NerdFontsEnabled() bool
NerdFontsEnabled reports whether Nerd Font symbols are enabled. Reads during Build, layout, or paint subscribe to changes in that phase.
func OpenURL ¶ added in v0.17.0
OpenURL asks the operating system to open an absolute HTTP or HTTPS URL in the user's default browser. It supports macOS, Linux (with xdg-open), and Windows. The URL is passed directly to the launcher without using a shell.
OpenURL waits for the launcher to exit and returns validation, unsupported platform, or launcher errors. Success means the launcher accepted the request; it does not mean the browser loaded the page. It does not suspend the UI or attach the launcher to the terminal. Use a background task to avoid blocking the UI while the launcher runs.
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 PrintAbove ¶ added in v0.21.0
func PrintAbove(w Widget)
PrintAbove renders w at the terminal's width and writes it above the live region of an inline app (see RunInline), where it stays in the terminal's scrollback. w is laid out with its height loose: Auto heights follow its content (up to 1000 rows), so avoid Flex heights.
It is safe to call from any goroutine; w is printed with the next frame. With no app running it prints w to stdout, like Print. A fullscreen app (Run) has nothing above it, so there it does nothing.
func PrintAboveText ¶ added in v0.21.0
func PrintAboveText(text string)
PrintAboveText writes text above the live region of an inline app, like PrintAbove. text may contain ANSI styling. Each line takes one row: lines wider than the terminal are cut off (print a wrapping Text with PrintAbove to wrap them), and a single trailing newline is ignored.
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 ReadClipboard ¶ added in v0.16.0
func ReadClipboard(selection ClipboardSelection, fn func(content string))
ReadClipboard reads the selected clipboard and calls fn with its contents on the event loop. It returns without waiting and does nothing unless an app is running.
In a local session with a paste tool (pbpaste, wl-paste, xclip, xsel, or PowerShell's Get-Clipboard on Windows and WSL), the tool's output is delivered. Otherwise ReadClipboard asks the terminal with an OSC 52 query, wrapped for tmux or screen. Reading through the terminal needs OSC 52 read support, which many terminals leave off or ask the user to allow, so fn may never be called. Don't block on it.
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. Outside a running app, a preceding RequestFocus call instead selects that widget, if it is focusable in this tree. The request is consumed by this render, including invalid IDs. Requests made during rendering stay within this render; a running app's pending request is preserved and is not used to focus the snapshot.
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. It takes over the whole window, in the alternate screen. The root widget can implement KeyHandler to receive key events that bubble up from focused descendants.
func RunExternal ¶ added in v0.16.0
RunExternal runs an interactive program, such as $EDITOR or $PAGER, in the terminal. It suspends the UI (leaving the alternate screen and handing the terminal's input back), runs cmd until it exits, then restores the UI and redraws it. It returns cmd's error.
A nil Stdin, Stdout or Stderr on cmd is connected to the terminal.
RunExternal blocks the event loop, so call it from a key, click or other event handler, or from a Dispatch callback, not from a background goroutine. With no app running it just runs cmd.
func RunInline ¶ added in v0.21.0
func RunInline(root Widget, opts InlineOptions) error
RunInline runs root in the normal screen below the cursor, like a CLI prompt, and blocks until it exits. The app lives in a region that starts on the cursor's row and is as tall as its content (root's height and any overlay reaching below it), up to opts.MaxHeight. The terminal's scrollback above it stays as it was; PrintAbove adds to it.
Sixel images position themselves absolutely, so they don't work inline.
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 Select ¶ added in v0.7.0
func Select[T, R comparable](s Signal[T], fn func(T) R) R
Select returns fn applied to the signal's current value. Read during a tracked phase, it subscribes the widget only to changes in that result: after a Set, the widget is notified only if fn gives a different answer.
This lets many widgets watch one signal while only the affected ones update. For example, each list row can ask whether it is the active row, so moving the cursor notifies just the old and new rows:
active := Select(state.CursorIndex, func(i int) bool { return i == row })
fn runs on every Set of the signal, so it must be cheap and pure, and must not read other signals.
func SelectAny ¶ added in v0.7.0
func SelectAny[T any, R comparable](s AnySignal[T], fn func(T) R) R
SelectAny is Select for an AnySignal.
func SetClipboard ¶ added in v0.5.0
func SetClipboard(selection ClipboardSelection, content string)
SetClipboard copies content to the selected clipboard. It is safe to call from any goroutine, and copies apply in call order. While an app runs it returns without waiting, and Run lets queued copies finish (for up to two seconds) before it returns. With no app running it returns once the copy is done, so a program can exit straight after.
In a local session (not over SSH) with a clipboard tool for the platform, the tool gets the content: pbcopy on macOS, clip.exe on Windows and WSL, wl-copy under Wayland, and xclip or xsel under X11. If no tool applies or it fails, SetClipboard falls back to the terminal: inside tmux it loads a tmux buffer with `tmux load-buffer -w`, which tmux 3.2+ forwards to the outer terminal's clipboard, and also sends OSC 52 through tmux passthrough; inside screen it sends OSC 52 through screen passthrough; elsewhere it sends OSC 52 directly. OSC 52 is written between frames and needs a running app; terminals without OSC 52 support ignore it.
macOS and Windows have no primary selection, so PrimaryClipboard goes straight to the terminal there. SetClipboardMethod can restrict the order to the tool or to the terminal. Failures are logged with Log.
In a Go test binary, ClipboardAuto runs no tool and only queues OSC 52. Call SetClipboardMethod(ClipboardNative) to run tools in a test.
func SetClipboardMethod ¶ added in v0.21.0
func SetClipboardMethod(m ClipboardMethod)
SetClipboardMethod chooses how SetClipboard and ReadClipboard reach the clipboard, for apps that let users override ClipboardAuto.
func SetCursorBlink ¶ added in v0.16.0
func SetCursorBlink(enabled bool)
SetCursorBlink turns blinking of the text cursor in TextInput and TextArea on or off for the whole app. It is off by default (a steady cursor). The default style is classic on/off blinking; use SetCursorBlinkStyle to select a smooth pulse instead. Typing, pasting, clicking and changing focus restore full brightness briefly. Animation updates only the cached cursor cell, without building, measuring, painting widgets or running text highlighters.
func SetCursorBlinkStyle ¶ added in v0.22.1
func SetCursorBlinkStyle(style CursorBlinkStyle)
SetCursorBlinkStyle selects classic blinking or smooth pulsing for the whole app. It does not enable blinking; use SetCursorBlink for that. Changing the style while blinking restarts the cursor at full brightness.
func SetCursorPulseConfig ¶ added in v0.26.0
func SetCursorPulseConfig(config CursorPulseConfig)
SetCursorPulseConfig configures the pulse for the whole app without changing the blink style or enabling blinking. It restarts the cursor at full brightness. The 400 ms hold after input is unchanged.
func SetDebugLogging ¶
func SetDebugLogging(enabled bool)
SetDebugLogging enables or disables debug logging. Logging is enabled by default when InitLogger is called.
func SetNerdFontsEnabled ¶ added in v0.26.0
func SetNerdFontsEnabled(enabled bool)
SetNerdFontsEnabled turns Nerd Font symbols on or off for the whole app. They are off by default. When disabled, NerdFontSymbol returns its fallback. This setting does not replace glyphs written directly into strings.
Terma does not detect Nerd Font availability: there is no portable terminal query for it. Applications should enable it only from a user preference. Call this during setup or in an event handler, not during Build.
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 ThemeDisplayName ¶ added in v0.11.0
ThemeDisplayName turns a theme name such as "rose-pine" into "Rose Pine".
func ThemeNames ¶
func ThemeNames() []string
ThemeNames returns a slice of all registered theme names in alphabetical order.
func WriteTerminal ¶ added in v0.16.0
func WriteTerminal(seq string)
WriteTerminal queues a raw escape sequence (an OSC, a mode change, a bell) to be written to the terminal between frames. It is safe to call from any goroutine. Nothing is written if no app is running.
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 tracked render phase, the widget is automatically subscribed to future changes for that phase. 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
// TriggerAnywhere lets a trigger character open the popup mid-word, as
// in "https://api/users/$". By default a trigger only counts at the
// start of the text or after whitespace, so the "@" in an email address
// doesn't open it. Either way the query after the trigger ends at
// whitespace.
TriggerAnywhere bool
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 OuterBorder ¶ added in v0.21.0
func OuterBorder(color ColorProvider, decorations ...BorderDecoration) Border
OuterBorder creates a half-block border that fills the outer half of each edge cell, so the border sits flush with the widget's edge and none of the widget's background shows outside it.
▛▀▀▀▜ ▌ ▐ ▙▄▄▄▟
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.
┌───┐ │ │ └───┘
func TallBorder ¶ added in v0.23.0
func TallBorder(color ColorProvider, decorations ...BorderDecoration) Border
TallBorder creates a Textual-style tall border with thin strokes at the top and bottom of each cell, leaving extra visual space above and below content. The fractional-block sides use the parent background; the left side is reversed.
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 BorderOuter BorderTall )
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. This is a reactive value - reading it during Build() will cause the widget to rebuild when a keybind's key, name or visibility changes, whether from a focus change or from state the focused widget's Keybinds() reads, such as its selection.
While a chord is in progress (see PendingChord), only the keybinds that continue it are returned, keyed by the key presses still to come.
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. This is a reactive value - reading it during Build() will cause the widget to rebuild when focus changes.
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. This is a reactive value, but only the widgets whose answer changes are rebuilt: moving between two widgets notifies just those two.
func (BuildContext) PendingChord ¶ added in v0.22.0
func (ctx BuildContext) PendingChord() []string
PendingChord returns the key presses of the chord in progress, spelled as the keybind that started it writes them ("ctrl+k"), or nil when no chord is waiting for its next key. Like ActiveKeybinds, it is reactive.
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 is pressed by a left click, or 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. While the pointer is over it (which needs an ID), its background lightens. 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. A left click presses the button, then the Click callback is invoked. 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. Buffer dimensions remain the caller's responsibility unless it also implements ResizableCellBuffer.
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. While the pointer is over it (which needs an ID), its background lightens.
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 ClipboardMethod ¶ added in v0.21.0
type ClipboardMethod int32
ClipboardMethod chooses how SetClipboard and ReadClipboard reach the clipboard.
const ( // ClipboardAuto uses the system clipboard tool in a local session, then // the tmux buffer, then OSC 52. It is the default. In a Go test binary it // acts as [ClipboardTerminal], so tests never overwrite the developer's // clipboard. ClipboardAuto ClipboardMethod = iota // ClipboardNative uses only the system clipboard tool and the tmux // buffer, and never OSC 52. ClipboardNative // ClipboardTerminal uses only OSC 52, wrapped for tmux or screen when // running inside one. ClipboardTerminal )
type ClipboardSelection ¶ added in v0.5.0
type ClipboardSelection = byte
ClipboardSelection identifies which terminal clipboard selection to target.
Common values are SystemClipboard and PrimaryClipboard.
const ( // SystemClipboard targets the terminal's system clipboard. SystemClipboard ClipboardSelection = ansi.SystemClipboard // PrimaryClipboard targets the terminal's primary selection. PrimaryClipboard ClipboardSelection = ansi.PrimaryClipboard )
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
MouseWheel func(MouseEvent) bool // Return true to consume wheel input before scrolling or bubbling
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) BuildContainerLayoutNode ¶ added in v0.5.0
func (c Column) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
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) OnMouseWheel ¶ added in v0.17.0
func (c Column) OnMouseWheel(event MouseEvent) bool
OnMouseWheel invokes the optional consumable wheel callback.
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..."
AnchorID string // Widget to anchor to; overrides Position when set
Anchor AnchorPoint // Where to anchor (default: AnchorBottomLeft)
Position FloatPosition // Screen position when AnchorID is empty (default: FloatPositionTopCenter)
Offset Offset // Adjustment from anchor or screen position
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
Current bool // The level's current value (e.g. the active theme), marked with a check; the cursor rests here while the query is empty
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 ThemePaletteItems ¶ added in v0.11.0
func ThemePaletteItems(onSelect func(themeName string)) []CommandPaletteItem
ThemePaletteItems returns command palette items for every registered theme, grouped under "Dark Themes" and "Light Themes" dividers. Each item shows a ThemeSwatch hint, is Current when it is the active theme, and carries the theme name in Data so an OnCursorChange handler can preview it. onSelect is called with the chosen theme's name.
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
// contains filtered or unexported fields
}
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. By default, the palette resets to the root level for the next open. Pass true to keep the current position.
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 ContainerLayoutBuilder ¶ added in v0.5.0
type ContainerLayoutBuilder interface {
BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
}
ContainerLayoutBuilder is the preferred layout API for container widgets. The framework builds child layout nodes first, then passes them to the container so it only needs to describe how those children are arranged.
Children are supplied in the widget's logical child order, matching ChildProvider/extractChildren ordering.
LayoutNodeBuilder remains supported as a compatibility fallback, especially for leaf widgets and older custom containers that still build child layout nodes manually inside BuildLayoutNode.
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 CursorBlinkStyle ¶ added in v0.22.1
type CursorBlinkStyle int32
CursorBlinkStyle controls how an enabled text cursor blinks.
const ( // CursorBlinkClassic alternates between a shown and hidden cursor (the default). CursorBlinkClassic CursorBlinkStyle = iota // CursorBlinkPulse smoothly dims the cursor using [CursorPulseConfig]. CursorBlinkPulse )
func CurrentCursorBlinkStyle ¶ added in v0.22.1
func CurrentCursorBlinkStyle() CursorBlinkStyle
CurrentCursorBlinkStyle returns the selected style, even if blinking is off.
type CursorProvider ¶ added in v0.20.0
CursorProvider positions the terminal cursor relative to the widget's border box. A hidden cursor still positions input-method candidate windows.
type CursorPulseConfig ¶ added in v0.26.0
type CursorPulseConfig struct {
// MinOpacity is the cursor's minimum blend into its background, from 0 to 1.
// Zero allows it to fade completely; 1 keeps it at full brightness.
// The app default is 0.35. Values are clamped to [0, 1]; NaN uses the default.
MinOpacity float64
// Easing applies separately to each half-cycle: full to minimum brightness,
// then minimum to full. Nil uses EaseInOutSine, the app default.
// Overshooting curves are clamped to keep opacity within the configured range.
Easing EasingFunc
// Period is the duration of a complete full → minimum → full cycle.
// Zero or negative values use the default of 1600 ms. The 400 ms hold after
// input is separate and does not scale with Period.
Period time.Duration
}
CursorPulseConfig controls CursorBlinkPulse for TextInput and TextArea.
func CurrentCursorPulseConfig ¶ added in v0.26.0
func CurrentCursorPulseConfig() CursorPulseConfig
CurrentCursorPulseConfig returns the pulse settings, even if blinking is off. Modify the returned copy and call SetCursorPulseConfig to update one setting while preserving the others.
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) OnMouseDown ¶ added in v0.11.0
func (d DirectoryTree) OnMouseDown(event MouseEvent)
OnMouseDown moves the cursor, toggles expansion or selects, as Tree does.
func (DirectoryTree) OnMouseMove ¶ added in v0.11.0
func (d DirectoryTree) OnMouseMove(event MouseEvent)
OnMouseMove drags the cursor, as Tree does.
func (DirectoryTree) OnMouseUp ¶ added in v0.11.0
func (d DirectoryTree) OnMouseUp(event MouseEvent)
OnMouseUp ends a drag, as Tree does.
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) BuildContainerLayoutNode ¶ added in v0.5.0
func (d Dock) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
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 Draggable ¶ added in v0.20.0
type Draggable[T any] struct { ID string Payload T Child Widget HandleID string // Shadow defaults to a soft dark shadow. A transparent color disables it. Shadow *FloatShadow // contains filtered or unexported fields }
Draggable lifts Child under the pointer after a left-button movement of one cell. ID must be stable and unique. HandleID optionally restricts the gesture to one descendant. Without a handle, focusable descendants keep their input.
func (Draggable[T]) Build ¶ added in v0.20.0
func (d Draggable[T]) Build(BuildContext) Widget
func (Draggable[T]) GetContentDimensions ¶ added in v0.20.0
type DropTarget ¶ added in v0.20.0
DropTarget receives payloads from Draggable with the same type parameter. Accept must have no side effects. OnDrop runs once on a valid release; it owns any application-state changes, including removing or moving the source.
func (DropTarget[T]) Build ¶ added in v0.20.0
func (d DropTarget[T]) Build(BuildContext) Widget
func (DropTarget[T]) GetContentDimensions ¶ added in v0.20.0
func (d DropTarget[T]) GetContentDimensions() (Dimension, Dimension)
func (DropTarget[T]) WidgetID ¶ added in v0.20.0
func (d DropTarget[T]) WidgetID() string
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 Field ¶ added in v0.20.0
type Field struct {
Label string
Help string
State *FieldState
Child Widget
Style Style
}
Field composes a label, input, help and visible errors. Direct TextInput and TextArea values/pointers and Checkbox pointers receive the state's input ID and blur tracking. Custom inputs should use InputID and call Touch on blur. A nil State is a presentation-only field.
func (Field) Build ¶ added in v0.20.0
func (f Field) Build(ctx BuildContext) Widget
func (Field) GetContentDimensions ¶ added in v0.20.0
type FieldBinding ¶ added in v0.20.0
type FieldBinding[T comparable] struct { Read func() T Write func(T) }
FieldBinding connects field metadata to an existing value source. Read must read that source reactively; Write restores it on Reset. Both are required. Use stable, reflexive comparable values (for example strings, bools or IDs).
type FieldState ¶ added in v0.20.0
type FieldState struct {
// contains filtered or unexported fields
}
FieldState owns validation visibility and an accepted baseline, not the input value. Construct it once outside Build and explicitly register it with a form.
func NewFieldState ¶ added in v0.20.0
func NewFieldState[T comparable](inputID string, binding FieldBinding[T], validators ...Validator[T]) *FieldState
NewFieldState binds an existing value and ordered validators to an input ID. Empty IDs and incomplete bindings panic because they are configuration errors.
func NewTextAreaField ¶ added in v0.20.0
func NewTextAreaField(inputID string, input *TextAreaState, validators ...Validator[string]) *FieldState
NewTextAreaField binds a field to an existing multiline input.
func NewTextInputField ¶ added in v0.20.0
func NewTextInputField(inputID string, input *TextInputState, validators ...Validator[string]) *FieldState
NewTextInputField binds a field to an existing single-line input. The binding reads Content reactively, unlike TextInputState.GetText's non-reactive read.
func (*FieldState) Accept ¶ added in v0.20.0
func (s *FieldState) Accept()
Accept retains the current value as the new baseline and clears touched/error visibility. Call after loading or successfully saving an accepted value.
func (*FieldState) Dirty ¶ added in v0.20.0
func (s *FieldState) Dirty() bool
Dirty compares the current value with the accepted baseline. It is reactive.
func (*FieldState) Enabled ¶ added in v0.20.0
func (s *FieldState) Enabled() bool
Enabled reports whether the field participates in form validation.
func (*FieldState) Errors ¶ added in v0.20.0
func (s *FieldState) Errors() []string
Errors returns the current visible errors, in validator order. Until Touch or Validate reveals errors, or while disabled, it returns nil. It is reactive.
func (*FieldState) InputID ¶ added in v0.20.0
func (s *FieldState) InputID() string
InputID returns the stable focus target assigned to adapted inputs.
func (*FieldState) Reset ¶ added in v0.20.0
func (s *FieldState) Reset()
Reset restores the accepted baseline and clears touched/error visibility. It does not call input callbacks. Use in handlers or setup, never during Build.
func (*FieldState) SetEnabled ¶ added in v0.20.0
func (s *FieldState) SetEnabled(enabled bool)
SetEnabled controls validation participation and Field's disabled presentation. Re-enabling preserves the value, baseline, touched and error visibility state.
func (*FieldState) Touch ¶ added in v0.20.0
func (s *FieldState) Touch()
Touch marks an enabled field as touched and reveals its current errors.
func (*FieldState) Touched ¶ added in v0.20.0
func (s *FieldState) Touched() bool
Touched reports whether the field has blurred since construction/Reset/Accept.
func (*FieldState) Valid ¶ added in v0.20.0
func (s *FieldState) Valid() bool
Valid checks the current value without revealing errors. Disabled fields are valid for form purposes. It tracks reactive source and validator dependencies.
func (*FieldState) Validate ¶ added in v0.20.0
func (s *FieldState) Validate() bool
Validate reveals current errors without marking the field touched.
type FileFilter ¶ added in v0.20.0
FileFilter matches basenames using filepath.Match. Empty Patterns matches all.
type FilePicker ¶ added in v0.20.0
type FilePicker struct {
ID string
State *FilePickerState
Mode FilePickerMode
Filters []FileFilter
MultiSelect bool
OnSelect func([]string)
OnCancel func()
Style Style
}
FilePicker selects paths; it never opens, writes, or deletes selected files. Give each mounted picker a stable ID. With a bounded height the list scrolls.
func (FilePicker) Build ¶ added in v0.20.0
func (p FilePicker) Build(ctx BuildContext) Widget
Build composes existing controls. It only reads reactive state; directory IO and selection changes belong to setup and handlers.
func (FilePicker) Cancel ¶ added in v0.20.0
func (p FilePicker) Cancel()
Cancel dismisses pending overwrite confirmation, or ends the current attempt once when no confirmation is open.
func (FilePicker) GetContentDimensions ¶ added in v0.20.0
func (p FilePicker) GetContentDimensions() (Dimension, Dimension)
func (FilePicker) GetStyle ¶ added in v0.20.0
func (p FilePicker) GetStyle() Style
func (FilePicker) Keybinds ¶ added in v0.20.0
func (p FilePicker) Keybinds() []Keybind
func (FilePicker) OnKey ¶ added in v0.20.0
func (p FilePicker) OnKey(KeyEvent) bool
func (FilePicker) Submit ¶ added in v0.20.0
func (p FilePicker) Submit() bool
Submit validates the current mode and paths, or requests explicit overwrite confirmation. True means OnSelect was emitted (or completion with nil callback).
func (FilePicker) WidgetID ¶ added in v0.20.0
func (p FilePicker) WidgetID() string
type FilePickerEntry ¶ added in v0.20.0
type FilePickerEntry struct {
Name, Path string
IsDir, IsSymlink bool
Err error
// contains filtered or unexported fields
}
FilePickerEntry is one direct child of the current directory. Err marks an unavailable entry (for example a broken symlink). Paths remain lexical.
type FilePickerFileSystem ¶ added in v0.20.0
type FilePickerFileSystem interface {
ReadDir(string) ([]fs.DirEntry, error)
Stat(string) (fs.FileInfo, error)
Lstat(string) (fs.FileInfo, error)
}
FilePickerFileSystem supplies directory listings and metadata. Implementations accept operating-system paths; the default delegates to os. It never writes.
type FilePickerMode ¶ added in v0.20.0
type FilePickerMode int
FilePickerMode determines the kind of path returned by a FilePicker.
const ( FilePickerOpen FilePickerMode = iota FilePickerSave FilePickerDirectory )
type FilePickerState ¶ added in v0.20.0
type FilePickerState struct {
Directory Signal[string]
Error Signal[string]
ShowHidden Signal[bool]
FilterIndex Signal[int]
PathInput *TextInputState
FilenameInput *TextInputState
// contains filtered or unexported fields
}
FilePickerState owns the current directory, editable path and filename, and selection. Construct once outside Build. Navigate and Refresh perform bounded, synchronous filesystem reads; Build never performs IO.
func NewFilePickerState ¶ added in v0.20.0
func NewFilePickerState(startDir string) *FilePickerState
func NewFilePickerStateWithFileSystem ¶ added in v0.20.0
func NewFilePickerStateWithFileSystem(startDir string, filesystem FilePickerFileSystem) *FilePickerState
NewFilePickerStateWithFileSystem supports deterministic or virtual filesystems. A nil filesystem uses the host OS. Initialization errors are available in Error.
func (*FilePickerState) Entries ¶ added in v0.20.0
func (s *FilePickerState) Entries() []FilePickerEntry
Entries returns a copy of the currently loaded direct children, before filtering.
func (*FilePickerState) Navigate ¶ added in v0.20.0
func (s *FilePickerState) Navigate(path string) error
Navigate reads one directory. A file path navigates to its parent and seeds filename/cursor. Failed navigation preserves the existing directory and rows.
func (*FilePickerState) Refresh ¶ added in v0.20.0
func (s *FilePickerState) Refresh() error
Refresh reloads the current directory and clears stale selections.
func (*FilePickerState) Reset ¶ added in v0.20.0
func (s *FilePickerState) Reset()
Reset starts a new selection attempt without changing the directory.
func (*FilePickerState) SelectPaths ¶ added in v0.20.0
func (s *FilePickerState) SelectPaths(paths ...string)
SelectPaths selects matching loaded entries. Submit still validates visibility and mode, so this cannot submit filtered or unavailable paths.
func (*FilePickerState) SelectedPaths ¶ added in v0.20.0
func (s *FilePickerState) SelectedPaths() []string
SelectedPaths returns loaded selected paths in directory display order.
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). Whitespace // separates terms, which may match in any order. Each match carries a // Score, and ranked consumers list the best matches first. 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 {
// Shadow paints a shadow or glow behind the float. Nil disables the effect.
Shadow *FloatShadow
// 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
// PointerPassthrough lets mouse clicks, dragging, wheel events and hover
// reach widgets beneath the float instead of its child subtree. The float
// also ignores outside-click dismissal. Useful for tooltips and previews.
// Modal takes precedence: modal floats always block pointer input.
// Keyboard focus and Escape dismissal are unaffected.
PointerPassthrough 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
// contains filtered or unexported fields
}
FloatConfig configures positioning and behavior for a floating widget.
type FloatEntry ¶
type FloatEntry struct {
Config FloatConfig
Child Widget
BuildChild func(BuildContext, FloatGeometry) Widget
// Computed position after layout (set during render phase)
X, Y int
Width, Height int
// contains filtered or unexported fields
}
FloatEntry stores a registered floating widget for deferred rendering.
type FloatGeometry ¶ added in v0.17.0
type FloatGeometry struct {
Screen Rect
// AnchorFound is false when AnchorID is empty or has not been laid out.
AnchorFound bool
// AnchorBounds can extend beyond the screen or a scroll viewport.
AnchorBounds Rect
// AnchorVisibleBounds is clipped by ancestor viewports and the screen.
// It can be empty even when AnchorFound is true.
AnchorVisibleBounds Rect
}
FloatGeometry is a current-frame snapshot supplied to Floating.BuildChild. All rectangles use screen coordinates, in terminal cells. The anchor's border box excludes margin and includes padding and border.
Only the main tree and earlier overlays are available. The overlay being built has not been measured yet; using its own future size here would create a layout cycle. Use FloatConfig.Anchor to align the completed overlay instead.
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 FloatShadow ¶ added in v0.20.0
FloatShadow tints the cells behind a floating widget without changing its size or pointer area. Dimensions are terminal cells. A zero Offset makes a glow.
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
// BuildChild builds overlay content after the main tree has been laid out.
// Geometry contains the current frame's screen and anchor bounds, so content
// can use the anchor's size without an OnLayout or Render cache. When set,
// BuildChild takes precedence over Child. Signal reads are tracked just as
// in Widget.Build. Do not mutate signals in this function.
BuildChild func(BuildContext, FloatGeometry) 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. Nested floats stay above their parent and below later sibling floats.
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) CollectGlobalKeybinds ¶ added in v0.11.0
func (fc *FocusCollector) CollectGlobalKeybinds(widget Widget, ctx BuildContext)
CollectGlobalKeybinds records the widget's global keybinds, if it has any.
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, KeybindProvider or PasteHandler.
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 the declarative keybindings a key press can reach now: the focused widget's, its ancestors', then the root widget's, in the order key handling checks them.
A keybind is left out when key handling would never get to it:
- an earlier widget binds its first key press, or, for an ancestor's keybind, the focused widget captures that key (KeyCapturer), so it doesn't bubble up;
- it runs an action on a key press that also starts a chord in the same widget, where the chord wins. A group label (no Action) stays.
While a chord is in progress, only the keybinds that continue it are returned, keyed by the key presses still to come.
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) HandlePaste ¶ added in v0.16.0
func (fm *FocusManager) HandlePaste(text string) bool
HandlePaste passes pasted text to the focused widget, then bubbles it up through the focused widget's ancestors. It reports whether any handled it.
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 Form ¶ added in v0.20.0
Form provides submission coordination around an ordinary widget subtree. Enter from an unconfigured Field TextInput and Ctrl+S submit through declarative keybindings. Child keybindings and explicit input OnSubmit handlers win.
func (Form) Build ¶ added in v0.20.0
func (f Form) Build(BuildContext) Widget
func (Form) GetContentDimensions ¶ added in v0.20.0
func (Form) Keybinds ¶ added in v0.20.0
Keybinds exposes submission while preserving child-specific Enter behaviour.
type FormState ¶ added in v0.20.0
type FormState struct {
// contains filtered or unexported fields
}
FormState is an explicit ordered registry of fields. It does not discover the widget tree: remove or disable hidden/unmounted fields that must not validate. State mutations and submission run on the UI event loop, like input callbacks.
func NewFormState ¶ added in v0.20.0
func NewFormState(fields ...*FieldState) *FormState
NewFormState registers fields in validation and first-invalid focus order. Nil entries are ignored and repeated pointers de-duplicated. Distinct states sharing one input ID panic because focus would otherwise be ambiguous.
func (*FormState) Accept ¶ added in v0.20.0
func (s *FormState) Accept()
Accept accepts current values and clears validation metadata on all fields.
func (*FormState) Dirty ¶ added in v0.20.0
Dirty reports whether any enabled field differs from its accepted baseline.
func (*FormState) Fields ¶ added in v0.20.0
func (s *FormState) Fields() []*FieldState
Fields returns a reactive defensive copy of the ordered registry.
func (*FormState) Reset ¶ added in v0.20.0
func (s *FormState) Reset()
Reset restores all registered fields, including disabled ones, to baseline.
func (*FormState) SetFields ¶ added in v0.20.0
func (s *FormState) SetFields(fields ...*FieldState)
SetFields atomically replaces the registry after checking identities. It leaves removed fields' values and metadata unchanged. Never call during Build.
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
// Source distinguishes pointer input from layout reconciliation. Both sources
// update hovered state and dispatch leave before enter when the target changes.
Source HoverEventSource
// 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 HoverEventSource ¶ added in v0.17.0
type HoverEventSource int
HoverEventSource identifies what caused a hover transition.
const ( // HoverSourcePointer indicates a transition resolved from mouse motion input, // including motion reports that change only the button or modifier state. // It is the zero value for compatibility with manually constructed events. HoverSourcePointer HoverEventSource = iota // HoverSourceLayout indicates a transition resolved after rendering at the // last known pointer position, without new pointer input. For example, a // widget appeared, disappeared, moved, or changed its hit-testing behavior. HoverSourceLayout )
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 Image ¶ added in v0.19.0
type Image struct {
ID string
Source *ImageResource
Fit ImageFit
Style Style
}
Image displays a static decoded image. Its logical representation is always coloured half blocks, including in snapshots and screen exports.
func (Image) Build ¶ added in v0.19.0
func (i Image) Build(BuildContext) Widget
func (Image) BuildLayoutNode ¶ added in v0.19.0
func (i Image) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
func (Image) GetContentDimensions ¶ added in v0.19.0
func (Image) Render ¶ added in v0.19.0
func (i Image) Render(ctx *RenderContext)
type ImageFit ¶ added in v0.19.0
type ImageFit uint8
ImageFit controls scaling within an Image's content box.
type ImageResource ¶ added in v0.19.0
type ImageResource struct {
// contains filtered or unexported fields
}
ImageResource is an immutable, decoded image. Construct it once and share it between widgets and frames. The source's pixels are copied, never retained.
func NewImageResource ¶ added in v0.19.0
func NewImageResource(source image.Image) (*ImageResource, error)
NewImageResource copies a nonempty image into zero-origin, straight-alpha storage.
type InlineExit ¶ added in v0.21.0
type InlineExit int
InlineExit is what happens to an inline app's live region when it exits.
const ( // InlineExitKeep leaves the final frame in the scrollback, with the // cursor on the line below it. InlineExitKeep InlineExit = iota // InlineExitClear erases the live region, leaving the cursor where the // region started. InlineExitClear )
type InlineOptions ¶ added in v0.21.0
type InlineOptions struct {
// MaxHeight caps the live region's rows. 0 means the terminal height.
// Root is laid out with Loose(width, maxHeight): Auto heights follow
// content, Flex fills MaxHeight.
MaxHeight int
// Mouse enables mouse reporting. Off by default inline, because it takes
// the wheel away from the terminal's own scrollback.
Mouse bool
// OnExit decides what happens to the live region when the app exits.
OnExit InlineExit
}
InlineOptions configures RunInline.
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. Cursor and trigger positions are grapheme indexes, matching TextInputState and TextAreaState.
var InsertAtCursor InsertStrategy = func(text string, cursor int, suggestion Suggestion, triggerPos int) (string, int) { value := suggestion.Value if value == "" { value = suggestion.Label } graphemes := splitGraphemes(text) if cursor > len(graphemes) { cursor = len(graphemes) } if cursor < 0 { cursor = 0 } prefix := joinGraphemes(graphemes[:cursor]) + value return prefix + joinGraphemes(graphemes[cursor:]), len(splitGraphemes(prefix)) }
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 } graphemes := splitGraphemes(text) if triggerPos < 0 { triggerPos = 0 } if triggerPos > len(graphemes) { triggerPos = len(graphemes) } if cursor > len(graphemes) { cursor = len(graphemes) } prefix := joinGraphemes(graphemes[:triggerPos]) + value return prefix + joinGraphemes(graphemes[cursor:]), len(splitGraphemes(prefix)) }
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, len(splitGraphemes(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 } graphemes := splitGraphemes(text) if cursor > len(graphemes) { cursor = len(graphemes) } if cursor < 0 { cursor = 0 } wordStart := cursor for wordStart > 0 { r, _ := utf8.DecodeRuneInString(graphemes[wordStart-1]) if unicode.IsSpace(r) { break } wordStart-- } wordEnd := cursor for wordEnd < len(graphemes) { r, _ := utf8.DecodeRuneInString(graphemes[wordEnd]) if unicode.IsSpace(r) { break } wordEnd++ } prefix := joinGraphemes(graphemes[:wordStart]) + value return prefix + joinGraphemes(graphemes[wordEnd:]), len(splitGraphemes(prefix)) }
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 IntrinsicContentSizer ¶ added in v0.5.0
IntrinsicContentSizer is implemented by widgets that can report their content size without rebuilding structural parents. This is used to decide whether a paint-only signal change can stay paint-only for auto-sized widgets.
type JSONNode ¶ added in v0.26.0
type JSONNode struct {
Path string // RFC 9535 normalized JSONPath, e.g. $['users'][2]['name'].
Label string // JSON-quoted object key, array index in brackets, or $ for the root.
Value any // map[string]any, []any, string, json.Number, bool, or nil.
// contains filtered or unexported fields
}
JSONNode is a value in a JSON document. Treat Value and its children as read-only.
type JSONViewer ¶ added in v0.26.0
type JSONViewer struct {
ID string
State *JSONViewerState
Style Style
DisableFocus bool
MultiSelect bool
ActivateOnClick bool
OnSelect func(node JSONNode, selected []JSONNode)
OnCursorChange func(node JSONNode)
}
JSONViewer displays a JSON document as a syntax-colored, scrollable Tree. Supply a State created with NewJSONViewerState. JSONPath input is deliberately separate: connect a TextInput's OnChange to State.SetQuery and display its error. Standard Tree keyboard and mouse navigation, expansion, and activation apply.
func (JSONViewer) Build ¶ added in v0.26.0
func (v JSONViewer) Build(ctx BuildContext) Widget
Build composes the viewer from Tree and Scrollable.
func (JSONViewer) GetStyle ¶ added in v0.26.0
func (v JSONViewer) GetStyle() Style
GetStyle exposes the viewport dimensions and styling to parent layouts.
func (JSONViewer) WidgetID ¶ added in v0.26.0
func (v JSONViewer) WidgetID() string
WidgetID returns the ID used to focus the viewer's tree.
type JSONViewerState ¶ added in v0.26.0
type JSONViewerState struct {
// Tree exposes navigation, expansion, and selection. Its Nodes are the current
// filtered view; use SetJSON rather than modifying them or their values.
Tree *TreeState[JSONNode]
// contains filtered or unexported fields
}
JSONViewerState owns a decoded document and its filtered tree. Create it once, outside Build. Use SetJSON and SetQuery from event handlers to change the view.
func NewJSONViewerState ¶ added in v0.26.0
func NewJSONViewerState(data []byte) (*JSONViewerState, error)
NewJSONViewerState decodes a single JSON value, preserving number lexemes. Invalid JSON returns an error and no state. Objects are sorted by key.
func (*JSONViewerState) MatchCount ¶ added in v0.26.0
func (s *JSONViewerState) MatchCount() int
MatchCount returns the number of distinct nodes selected by the query, subscribing to changes. An empty query selects the root (one match).
func (*JSONViewerState) Query ¶ added in v0.26.0
func (s *JSONViewerState) Query() string
Query returns the last valid query, subscribing to changes.
func (*JSONViewerState) SetJSON ¶ added in v0.26.0
func (s *JSONViewerState) SetJSON(data []byte) error
SetJSON replaces the document and reapplies the current query. Expansion, cursor, selection, and scrolling reset. Invalid JSON leaves the state intact.
func (*JSONViewerState) SetQuery ¶ added in v0.26.0
func (s *JSONViewerState) SetQuery(query string) error
SetQuery filters using RFC 9535 JSONPath. Empty or whitespace-only queries restore the whole document. Matches retain their ancestors and entire subtrees; array indices and paths always refer to the original document. Ancestors of matches expand, but can subsequently be collapsed using normal tree controls. Applying a different query resets cursor, selection, and scroll position. Invalid queries return an error without changing the last valid view.
type JumpState ¶ added in v0.11.0
type JumpState struct {
// contains filtered or unexported fields
}
JumpState holds the state of jump mode for a Jumper. Create it with NewJumpState and keep it for the life of the app.
func NewJumpState ¶ added in v0.11.0
func NewJumpState() *JumpState
NewJumpState creates a jump state with jump mode inactive.
func (*JumpState) Activate ¶ added in v0.11.0
func (s *JumpState) Activate()
Activate enters jump mode, labelling every target on screen.
func (*JumpState) Deactivate ¶ added in v0.11.0
func (s *JumpState) Deactivate()
Deactivate leaves jump mode without jumping.
func (*JumpState) IsActive ¶ added in v0.11.0
IsActive reports whether jump mode is active. Reading it during Build subscribes to changes.
type JumpTarget ¶ added in v0.11.0
type JumpTarget struct {
// Key is the text to type, usually one character such as "1" or "u".
// Longer keys ("gt") are typed one character at a time. No key should be
// a prefix of another, or the longer one can never be reached.
Key string
// ID is the widget to label and jump to. If it isn't focusable itself
// (a panel, say), the jump focuses the first focusable widget inside it.
ID string
// Action, if set, runs instead of moving focus: switching a tab, pressing
// a button, and so on. It is labelled at the widget with ID.
Action func()
}
JumpTarget is one entry in a static jump map: typing Key while jump mode is active jumps to the widget with the given ID.
type Jumpable ¶ added in v0.11.0
type Jumpable interface {
Jump()
}
Jumpable is implemented by the items inside a widget that dynamic jump hints label one by one: List rows, Tree nodes, Table rows (or cells, in cursor selection mode) and tabs. These are what dynamic hints are for, content that isn't known until the app runs.
Typing an item's hint calls Jump, then focuses the focusable widget holding the item, such as its List, unless Jump requested focus itself. Implement Jumpable on your own widgets to make them jump targets; Jump might select a card or open a link. A Jumpable rendered inside another, such as a custom List row, is labelled in place of the one holding it.
type Jumper ¶ added in v0.11.0
type Jumper struct {
State *JumpState // Required
Targets []JumpTarget // Static jump map
// Dynamic labels the rows, tabs and other Jumpable items in view, and
// any other focusable widget that isn't in Targets.
Dynamic bool
// Hints are the characters dynamic hints are made from.
// Defaults to DefaultJumpHints.
Hints string
// Key toggles jump mode. Defaults to DefaultJumpKey. It is bound on the
// Jumper, so it works while focus is anywhere inside Child. Call
// State.Activate from your own keybind to enter jump mode another way.
Key string
// Unmatched receives a key that matches no label, after jump mode has
// ended, so jump mode can share keys with commands of your own. Without
// it the key is dropped. Escape and Key only ever leave jump mode.
Unmatched func(KeyEvent)
Child Widget
// LabelStyle styles the labels. Unset colors default to the theme's
// accent; labels are always padded by one cell on each side.
LabelStyle Style
// Backdrop dims the screen beneath the labels. Defaults to a light tint
// of the theme's Overlay; use a fully transparent color to turn it off.
Backdrop Color
}
Jumper adds a jump mode to its Child, inspired by Posting's jump mode and Vimium's link hints. Pressing Key (ctrl+o by default) overlays a short label on each target; typing a label moves focus straight to its target. Escape, the toggle key, a click or any key that matches no label leaves jump mode; Unmatched can take that last key instead of it being dropped.
Targets come from two places, which can be combined:
- Targets is a static jump map. Each key always leads to the same widget, so it can be learned: "1" for the sidebar, "u" for the URL bar.
- Dynamic labels what is on screen that no key could be assigned to in advance, as Vimium does with links: each visible row of a List, Tree or Table, each tab, and anything else implementing Jumpable, plus any other focusable widget without a static key. Jumping to a row moves the cursor there and focuses its list. Hints are made from Hints, are as short as the number of targets allows, and are assigned in reading order. Longer hints are typed one character at a time, with the labels narrowing as you go.
Only widgets that are on screen are labelled. While focus is inside a modal (or any focus trap), only targets inside it are labelled. The overlay sits above every other overlay, and doesn't take focus: the focused widget keeps its focus styling while you choose where to go.
Example:
Jumper{
State: a.jump,
Targets: []JumpTarget{
{Key: "1", ID: "sidebar"},
{Key: "u", ID: "url"},
{Key: "r", ID: "response-tabs", Action: a.showResponse},
},
Dynamic: true,
Child: a.body(),
}
func (Jumper) Build ¶ added in v0.11.0
func (j Jumper) Build(ctx BuildContext) Widget
Build registers the label overlay while jump mode is active and returns Child unchanged, so a Jumper never affects layout.
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 or invoking built-in shortcuts such as Tab navigation, Ctrl+C, Ctrl+Z, and screen export. When it 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"
func (KeyEvent) Raw ¶ added in v0.20.0
func (k KeyEvent) Raw() uv.KeyPressEvent
Raw returns the key event, including modifiers and alternate key codes.
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".
// A character key matches its case: "D" is shift+d, "d" is d.
//
// A chord is several key presses separated by spaces, pressed one after
// the other: "ctrl+k ctrl+s", "g g", "space f". Inside a chord, write the
// space key as "space"; on its own, " " works too.
//
// A chord wins over a binding to its own start: with "g" and "g g" in the
// same widget, pressing g waits for the next key and "g" never runs.
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.
//
// A keybind with no Action whose Key starts other chords labels them as
// a group: {Key: "ctrl+k", Name: "Window"} collapses every "ctrl+k …"
// chord into one "ctrl+k Window…" hint in KeybindBar. Pressing ctrl+k then
// shows the group's chords.
Action func()
// Hidden prevents this keybind from appearing in KeybindBar.
// Use for internal bindings that shouldn't be displayed to users.
// A hidden group label hides its whole group.
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: Flex(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. The key may be a chord: key presses
// separated by spaces, such as "ctrl+k ctrl+s".
FormatKey func(string) string
}
KeybindBar displays available keybinds based on the currently focused widget. It shows keybinds from the focused widget and its ancestors in the widget tree, and updates when they change: on a focus change, or when state a Keybinds() method reads changes, such as a selection.
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").
Chords show their key presses in order ("ctrl+k ctrl+s Save all"). A group label (a keybind with no Action whose Key starts other chords) stands in for its chords as one hint, "ctrl+k Window…". While a chord is in progress the bar shows it, then the keys that can come next, then how to cancel: "ctrl+k … s Save all w Close all escape Cancel".
Hints that don't fit in the bar's width are left out, from the end, so the bar never draws past its box.
func (KeybindBar) Build ¶
func (f KeybindBar) Build(ctx BuildContext) Widget
Build constructs the keybind bar by collecting active keybinds from context.
func (KeybindBar) GetContentDimensions ¶ added in v0.16.0
func (f KeybindBar) GetContentDimensions() (width, height Dimension)
GetContentDimensions returns the width and height dimension preferences. Width defaults to Flex(1), filling the space its siblings leave. Height defaults to Cells(1), as KeybindBar is a single-line widget.
func (KeybindBar) GetStyle ¶ added in v0.16.0
func (f KeybindBar) GetStyle() Style
GetStyle returns the style.
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 or an item is double-clicked ActivateOnClick bool // Invoke OnSelect on a single left click instead of a double-click 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). Called per row; on cursor or selection changes only affected rows are re-rendered, so it should be free of side effects. 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, shift+click or drag 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 // contains filtered or unexported fields }
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 moves the cursor to the clicked item, extends the selection on shift+click in multi-select mode, and selects the item on double-click (or on a single click with ActivateOnClick). Implements the MouseDownHandler interface.
func (List[T]) OnMouseMove ¶ added in v0.11.0
func (l List[T]) OnMouseMove(event MouseEvent)
OnMouseMove drags the cursor to the item under the pointer while a press on an item is held, extending the selection from the pressed item in multi-select mode. Dragging past either end scrolls. Implements the MouseMoveHandler interface.
func (List[T]) OnMouseUp ¶
func (l List[T]) OnMouseUp(event MouseEvent)
OnMouseUp ends a drag begun on an item. 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]) Clear ¶
func (s *ListState[T]) Clear()
Clear removes all items from the list, along with the selection.
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. The cursor and selection stay on the same items.
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. The cursor and selection stay on the same items.
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. The removed item leaves the selection; other selected items stay selected.
func (*ListState[T]) RemoveWhere ¶
RemoveWhere removes all items matching the predicate. Returns the number of items removed. Removed items leave the selection; other selected items stay selected.
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. Selected indices past the end of the new items are dropped.
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 Markdown ¶ added in v0.20.0
type Markdown struct {
ID string
State *MarkdownState
Style Style
ScrollState *ScrollState // Optional: share the containing Scrollable's state to reveal keyboard-selected links.
CodeTheme string // Optional Chroma style name for fenced code syntax highlighting.
DisableFocus bool
OnLink func(destination string)
OnCopy func(text string) // Nil uses the terminal system clipboard.
}
Markdown displays CommonMark headings, paragraphs, lists, quotes, code and links. Compose with Scrollable for viewport scrolling. Absolute http, https and mailto links are written as OSC 8 terminal hyperlinks, which the terminal opens on its own link gesture. Keyboard and click activation never opens a URL itself; it calls OnLink, which can pass the destination to OpenURL. Ctrl+A selects all text; Y copies it, and Escape clears selection.
func (Markdown) Build ¶ added in v0.20.0
func (m Markdown) Build(ctx BuildContext) Widget
Build creates a width-aware view of the already parsed document.
type MarkdownState ¶ added in v0.20.0
type MarkdownState struct {
// contains filtered or unexported fields
}
MarkdownState owns an immutable parsed document and the viewer's selection. Construct it with NewMarkdownState and update it outside Build.
func NewMarkdownState ¶ added in v0.20.0
func NewMarkdownState(source string) *MarkdownState
NewMarkdownState parses source for a Markdown viewer.
func (*MarkdownState) Append ¶ added in v0.20.0
func (s *MarkdownState) Append(fragment string)
Append appends a fragment and reparses the document, including incomplete fences.
func (*MarkdownState) PlainText ¶ added in v0.20.0
func (s *MarkdownState) PlainText() string
PlainText returns logical rendered text, without viewport wrapping or Markdown syntax. It subscribes when called in a tracked phase.
func (*MarkdownState) SetSource ¶ added in v0.20.0
func (s *MarkdownState) SetSource(source string)
SetSource replaces the document and clears selection. Identical source is a no-op. Like other composite widget state, mutate it on the UI event loop.
func (*MarkdownState) Source ¶ added in v0.20.0
func (s *MarkdownState) Source() string
Source returns the source, subscribing when called in a tracked phase.
type MatchRange ¶
MatchRange defines a matched substring range [Start, End) in bytes.
type MatchResult ¶
type MatchResult struct {
Matched bool
Ranges []MatchRange
// Score ranks fuzzy matches; higher is better. Scores only compare between
// matches for the same query, and are zero outside FilterFuzzy. Between
// matches of equal quality, the one on shorter text scores higher.
Score int
}
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
// SubCellX and SubCellY place the pointer within its cell, from 0 (left or
// top edge) up to 1. They are exact when the terminal reports the pointer
// in pixels, and 0.5 (the cell's centre) otherwise.
SubCellX, SubCellY float64
}
MouseEvent wraps a mouse interaction with click-chain metadata. Wheel events use Button for direction and have ClickCount zero.
type MouseMoveHandler ¶
type MouseMoveHandler interface {
OnMouseMove(event MouseEvent)
}
MouseMoveHandler is implemented by widgets that respond to mouse movement during drag. It is called while a button pressed on the widget is held, wherever the pointer goes; LocalX and LocalY can then lie outside the widget.
type MouseUpHandler ¶
type MouseUpHandler interface {
OnMouseUp(event MouseEvent)
}
MouseUpHandler is implemented by widgets that respond to mouse button releases. A release goes to the widget that received the press, even if the pointer has since moved off it, so a drag always ends where it started.
type MouseWheelHandler ¶ added in v0.17.0
type MouseWheelHandler interface {
OnMouseWheel(event MouseEvent) bool
}
MouseWheelHandler receives wheel input over a widget or its descendants. Return true to consume the event. Returning false lets the widget's normal scrolling run, then bubbles to its ancestors, innermost first. Button is MouseWheelUp, MouseWheelDown, MouseWheelLeft or MouseWheelRight.
type PasteHandler ¶ added in v0.16.0
PasteHandler is implemented by widgets that accept pasted text.
Terma enables bracketed paste, so a paste arrives as one piece of text rather than as a burst of key presses (where each newline would be an Enter). It goes to the focused widget if that is a PasteHandler, and otherwise bubbles up through its ancestors that are. Return true if the paste was handled. A paste nothing handles is dropped.
type Pilot ¶ added in v0.21.0
type Pilot struct {
// contains filtered or unexported fields
}
Pilot drives an app in a test the way a user would: it presses keys, types, pastes, clicks and resizes, then lets you read the screen, the focused widget or the clipboard, or compare the screen against a snapshot.
A Pilot runs the app on the same retained renderer, focus manager and event routing that Run uses, with an in-memory screen in place of a terminal. After every input it draws frames until the app settles: work queued with Dispatch, signal updates, focus requests and modal focus all apply before the next call returns.
Time is frozen. Animations, spinners, shimmers and the cursor blink move only when Pilot.Advance moves the clock, so frames are deterministic. Background goroutines still run for real; use Pilot.WaitUntil to wait for the state they produce.
A Pilot stands in for the running app, so only one can exist at a time and tests that use one must not call t.Parallel.
func NewPilot ¶ added in v0.21.0
NewPilot starts root on a width×height screen and draws its first frame. The app stops when the test ends.
func (*Pilot) Advance ¶ added in v0.21.0
Advance moves the clock on by d. Running animations step a frame at a time at the app's frame rate, and the cursor uses its selected style if blinking is on.
func (*Pilot) AssertSnapshot ¶ added in v0.21.0
AssertSnapshot compares the screen with the golden file testdata/<TestName>_<name>.svg, as AssertSnapshot does for a widget. Run the tests with UPDATE_SNAPSHOTS=1 to write it.
func (*Pilot) Bounds ¶ added in v0.21.0
Bounds is the screen area of the widget with the given ID, and whether a widget with that ID was drawn.
func (*Pilot) Buffer ¶ added in v0.21.0
Buffer is the screen's cells, for checks the other methods don't cover.
func (*Pilot) Click ¶ added in v0.21.0
Click clicks the left mouse button in the middle of the visible part of the widget with the given ID. The click is hit tested like a real one, so a widget covered by an overlay doesn't receive it.
func (*Pilot) ClickAt ¶ added in v0.21.0
ClickAt presses and releases the left mouse button at screen cell (x, y). Clicks on the same cell form a double (or triple) click unless the clock moves on by more than half a second between them.
func (*Pilot) Clipboard ¶ added in v0.21.0
Clipboard is what the app last put on the system clipboard with SetClipboard. ReadClipboard reads it back.
func (*Pilot) Exited ¶ added in v0.21.0
Exited reports whether the app has quit, through Quit or ctrl+c.
func (*Pilot) FocusedID ¶ added in v0.21.0
FocusedID is the ID of the focused widget, or "" if nothing is focused.
func (*Pilot) Hover ¶ added in v0.21.0
Hover moves the pointer over the middle of the widget with the given ID.
func (*Pilot) Keybinds ¶ added in v0.21.0
Keybinds are the keybinds active for the focused widget and its ancestors, as a KeybindBar would show them (hidden ones included).
func (*Pilot) MouseDown ¶ added in v0.21.0
MouseDown presses a mouse button at (x, y) with the given modifiers held.
func (*Pilot) MouseMove ¶ added in v0.21.0
MouseMove moves the pointer to (x, y). Between MouseDown and MouseUp this drags.
func (*Pilot) Now ¶ added in v0.21.0
Now is the Pilot's clock. It starts at a fixed time and moves only with Pilot.Advance.
func (*Pilot) PointerShape ¶ added in v0.24.0
func (p *Pilot) PointerShape() PointerShape
PointerShape returns the mouse pointer requested by the app, as a terminal supporting OSC 22 would display it.
func (*Pilot) Press ¶ added in v0.21.0
Press presses each key in turn. Keys are spelled as in Keybind: "tab", "enter", "ctrl+s", "shift+down", "q", "?".
func (*Pilot) Resize ¶ added in v0.21.0
Resize resizes the screen, as when the terminal window changes size.
func (*Pilot) ScreenText ¶ added in v0.21.0
ScreenText is the screen as plain text, one line per row.
func (*Pilot) Scroll ¶ added in v0.21.0
Scroll turns the mouse wheel at (x, y) by lines notches: positive scrolls down, negative up.
func (*Pilot) Send ¶ added in v0.21.0
Send delivers raw terminal events (ultraviolet key, mouse, paste and window size events) through the app's event routing, settling after each. The helpers above cover common input; Send is for the rest, such as a click with modifiers or a key with unusual fields.
func (*Pilot) TextOf ¶ added in v0.21.0
TextOf is the plain text in the visible part of the widget with the given ID, one line per row with trailing spaces removed.
func (*Pilot) Type ¶ added in v0.21.0
Type types text one character at a time, as key presses. Use Pilot.Paste to deliver text in one piece.
type PointerShape ¶ added in v0.24.0
type PointerShape string
PointerShape is a mouse pointer shape from the Kitty OSC 22 protocol. Terminals without support leave the pointer unchanged. This does not change the text cursor. Set a widget's Style.Pointer to select a shape on hover.
const ( PointerInherit PointerShape = "" // Use the nearest ancestor's shape (the default). PointerDefault PointerShape = "default" PointerPointer PointerShape = "pointer" // A pointing hand. PointerText PointerShape = "text" PointerVerticalText PointerShape = "vertical-text" PointerHelp PointerShape = "help" PointerWait PointerShape = "wait" PointerProgress PointerShape = "progress" PointerCrosshair PointerShape = "crosshair" PointerCell PointerShape = "cell" PointerMove PointerShape = "move" PointerGrab PointerShape = "grab" PointerGrabbing PointerShape = "grabbing" PointerNotAllowed PointerShape = "not-allowed" PointerNoDrop PointerShape = "no-drop" PointerAlias PointerShape = "alias" PointerCopy PointerShape = "copy" PointerZoomIn PointerShape = "zoom-in" PointerZoomOut PointerShape = "zoom-out" PointerEWResize PointerShape = "ew-resize" PointerNSResize PointerShape = "ns-resize" PointerNESWResize PointerShape = "nesw-resize" PointerNWSEResize PointerShape = "nwse-resize" PointerNResize PointerShape = "n-resize" PointerNEResize PointerShape = "ne-resize" PointerEResize PointerShape = "e-resize" PointerSEResize PointerShape = "se-resize" PointerSResize PointerShape = "s-resize" PointerSWResize PointerShape = "sw-resize" PointerWResize PointerShape = "w-resize" PointerNWResize PointerShape = "nw-resize" )
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 PresentedText ¶ added in v0.5.0
type PresentedText struct {
LayoutText string
LayoutStyle Style
Wrap WrapMode
TextAlign TextAlign
CurrentLayoutText func() string
CurrentStyle func() Style
Paint func(*RenderContext) PresentedTextPaint
WidthHint func() int
HeightHint func(width int) int
// Underlay, if set, gives a translucent color laid over what is beneath
// the text before its own background is drawn. A translucent background
// composites over it; an opaque one hides it.
Underlay func(*RenderContext) Color
}
PresentedText is a small leaf helper for the common "stable layout, reactive paint" pattern. Layout uses LayoutText/LayoutStyle, while Paint may react to transient state such as cursor, focus, or selection.
func AnySignalMarkup ¶ added in v0.5.0
func AnySignalMarkup[T any](signal AnySignal[T], format func(T) string) PresentedText
AnySignalMarkup renders an AnySignal's formatted value as reactive markup.
func AnySignalText ¶ added in v0.5.0
func AnySignalText[T any](signal AnySignal[T], format func(T) string) PresentedText
AnySignalText renders an AnySignal's formatted value as reactive text.
func ComputedSpans ¶ added in v0.5.0
func ComputedSpans(layoutText string, compute func(theme ThemeData) []Span) PresentedText
ComputedSpans creates a PresentedText whose visible spans are recomputed at paint time, while layout remains based on the provided stable layout text.
func ComputedText ¶ added in v0.5.0
func ComputedText(layoutText string, compute func() string) PresentedText
ComputedText creates a PresentedText whose visible content is recomputed at paint time, while layout remains based on the provided stable layout text.
func PresentHighlightedText ¶ added in v0.5.0
func PresentHighlightedText(layoutText string, layoutStyle Style, currentStyle func() Style, paintStyle func(*RenderContext) Style, match func(*RenderContext) MatchResult) PresentedText
PresentHighlightedText creates a PresentedText that highlights matched text ranges during paint while keeping layout stable.
func PresentPrefixedText ¶ added in v0.5.0
func PresentPrefixedText(layoutText, content string, layoutStyle Style, currentStyle func() Style, paintStyle func(*RenderContext) Style, prefix func(*RenderContext) string, match func(*RenderContext) MatchResult) PresentedText
PresentPrefixedText creates a PresentedText that prepends a paint-phase prefix while keeping layout stable. Highlight ranges apply only to the main content, not the prefix.
func PresentStyledText ¶ added in v0.5.0
func PresentStyledText(layoutText string, layoutStyle Style, currentStyle func() Style, paintStyle func(*RenderContext) Style) PresentedText
PresentStyledText creates a PresentedText whose paint output is the layout text with a paint-phase style.
func PresentText ¶ added in v0.5.0
func PresentText(layoutText string, layoutStyle Style, currentStyle func() Style, paint func(*RenderContext) PresentedTextPaint) PresentedText
PresentText creates a PresentedText with a custom paint callback.
func SignalMarkup ¶ added in v0.5.0
func SignalMarkup[T comparable](signal Signal[T], format func(T) string) PresentedText
SignalMarkup renders a comparable signal's formatted value as reactive markup. The markup string is reparsed during paint, while layout sizing follows the current peeked plain-text content.
func SignalText ¶ added in v0.5.0
func SignalText[T comparable](signal Signal[T], format func(T) string) PresentedText
SignalText renders a comparable signal's formatted value as reactive text. The signal is tracked in the paint phase, while layout sizing follows the current peeked text so auto-sized uses can still promote to layout correctly.
func (PresentedText) Build ¶ added in v0.5.0
func (t PresentedText) Build(ctx BuildContext) Widget
func (PresentedText) BuildLayoutNode ¶ added in v0.5.0
func (t PresentedText) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
func (PresentedText) ContentHeightHint ¶ added in v0.5.0
func (t PresentedText) ContentHeightHint(width int) int
func (PresentedText) ContentWidthHint ¶ added in v0.5.0
func (t PresentedText) ContentWidthHint() int
func (PresentedText) GetContentDimensions ¶ added in v0.5.0
func (t PresentedText) GetContentDimensions() (width, height Dimension)
func (PresentedText) GetStyle ¶ added in v0.5.0
func (t PresentedText) GetStyle() Style
func (PresentedText) Render ¶ added in v0.5.0
func (t PresentedText) Render(ctx *RenderContext)
type PresentedTextPaint ¶ added in v0.5.0
PresentedTextPaint describes the concrete text payload a PresentedText leaf should draw during the paint phase.
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.
func (Rect) Intersect ¶
Intersect returns the intersection of two rectangles. Returns a zero-size rect if they don't overlap.
func (Rect) Intersects ¶ added in v0.5.0
Intersects returns true if two rectangles overlap.
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) DrawCells ¶ added in v0.20.0
func (ctx *RenderContext) DrawCells(x, y int, cells []uv.Cell)
DrawCells draws a row of terminal cells relative to the context. The slice contains one entry per column, including width-zero wide-cell continuations. A wide glyph cut by the widget's visible boundary becomes styled spaces. Repainting either column of a visible wide glyph redraws the entire glyph.
func (*RenderContext) DrawImage ¶ added in v0.19.0
func (ctx *RenderContext) DrawImage(x, y, width, height int, source *ImageResource, fit ImageFit)
DrawImage draws into a cell rectangle relative to this context. A nil Source draws nothing. Later cell painting covers native graphics, even identical writes.
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) IsFocusedID ¶ added in v0.5.0
func (ctx *RenderContext) IsFocusedID(id string) bool
IsFocusedID returns whether the given widget identity currently has focus. Unlike IsFocused(widget), this lets paint-only helper widgets react to focus changes for a parent widget without having to reuse that parent's WidgetID.
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 RenderStats ¶ added in v0.5.0
type RenderStats struct {
FrameMode string
FullRenderCount int
PartialRenderCount int
BuildCount int
LayoutCount int
PaintCount int
DamagedRects []Rect
}
RenderStats captures renderer activity for the most recent frame. These values are primarily intended for debugging and demos.
func CurrentRenderStats ¶ added in v0.5.0
func CurrentRenderStats() RenderStats
CurrentRenderStats returns debug information for the most recent frame. Returns zero values if no app is currently running.
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
// Disabled is true inside a DisabledWhen subtree, so the widget receives
// no presses or clicks.
Disabled bool
// 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
// contains filtered or unexported fields
}
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 renderer with the given viewport dimensions. If terminal implements ResizableCellBuffer, its dimensions are set to match. Otherwise the caller must provide a buffer large enough for the viewport. Negative dimensions are treated as zero.
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) PointerOwnerAt ¶ added in v0.11.0
func (r *Renderer) PointerOwnerAt(x, y int) *WidgetEntry
PointerOwnerAt returns the innermost widget at the given coordinates that is focusable or takes the pointer input landing on its descendants (such as a List, whose rows are separate widgets). Returns nil if there is none.
func (*Renderer) Render ¶
func (r *Renderer) Render(root Widget) []FocusableEntry
Render renders the widget tree to the terminal and returns collected focusables. Outside a running app, work scheduled with Dispatch during rendering runs at frame boundaries, and the returned output includes those updates. A headless render panics if dispatched work fails to settle within 16 frames. 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. Headless Dispatch work settles as described by Render.
func (*Renderer) Resize ¶
Resize updates the viewport dimensions and requests a full frame on the next Render or Update. Buffers implementing ResizableCellBuffer are resized too; other buffers must be resized by the caller. Negative dimensions become zero.
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) Stats ¶ added in v0.5.0
func (r *Renderer) Stats() RenderStats
Stats returns a snapshot of the renderer's most recent frame activity.
func (*Renderer) TopFloat ¶
func (r *Renderer) TopFloat() *FloatEntry
TopFloat returns the topmost (last registered) float entry, or nil if none.
func (*Renderer) Update ¶ added in v0.5.0
func (r *Renderer) Update(root Widget) []FocusableEntry
Update renders the next frame using the retained tree when possible. Paint-only signal changes take the partial repaint fast path. Build and layout changes reuse clean builds, then lay out and paint the whole tree. Headless Dispatch work settles as described by Render.
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 ResizableCellBuffer ¶ added in v0.17.0
type ResizableCellBuffer interface {
CellBuffer
Resize(width, height int)
}
ResizableCellBuffer opts a cell buffer into renderer-controlled dimensions. NewRenderer and Renderer.Resize call Resize to match the requested viewport. *uv.Buffer implements this interface, including when embedded in a custom screen. *uv.Terminal does not: its Resize method returns an error, and the application updates its screen dimensions separately before resizing the renderer.
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
MouseWheel func(MouseEvent) bool // Return true to consume wheel input before scrolling or bubbling
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) BuildContainerLayoutNode ¶ added in v0.5.0
func (r Row) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
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) OnMouseWheel ¶ added in v0.17.0
func (r Row) OnMouseWheel(event MouseEvent) bool
OnMouseWheel invokes the optional consumable wheel callback.
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) PageDown ¶ added in v0.19.0
func (s *ScrollState) PageDown() bool
PageDown scrolls down by the viewport height, gliding there so the eye can follow the content. Pages requested during the glide add up. It calls OnScrollDown and reports the result as ScrollDown does.
func (*ScrollState) PageUp ¶ added in v0.19.0
func (s *ScrollState) PageUp() bool
PageUp scrolls up by the viewport height, gliding there so the eye can follow the content. Pages requested during the glide add up. It calls OnScrollUp and reports the result as ScrollUp does.
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.
While a page scroll animation runs, the region is measured against where the viewport is heading, and the animation is retargeted rather than cut short, so moving the cursor during a glide doesn't make the viewport jump.
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. It stops any scroll animation in progress.
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
MouseWheel func(MouseEvent) bool // Return true to consume wheel input before scrolling or bubbling
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; alpha 0 hides the track (default: theme.ScrollbarTrack)
// ScrollbarFadeDelay enables idle fading when positive. The scrollbar is
// initially visible, then fades after this much inactivity. Scrolling or
// dragging reveals it immediately; its column always stays reserved.
// Zero (the default) or a negative delay leaves it always visible.
ScrollbarFadeDelay time.Duration
// ScrollbarFadeDuration is the fade-out time (default: 250ms).
ScrollbarFadeDuration time.Duration
}
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) BuildContainerLayoutNode ¶ added in v0.5.0
func (s Scrollable) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
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) OnMouseWheel ¶ added in v0.17.0
func (s Scrollable) OnMouseWheel(event MouseEvent) bool
OnMouseWheel invokes the optional consumable wheel callback.
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 SelectBox ¶ added in v0.20.0
type SelectBox[T comparable] struct { ID string State *SelectState[T] Options []SelectOption[T] Placeholder string Searchable bool Disabled bool MaxVisible int // Maximum visible option rows; defaults to 8. Style Style PopupStyle Style OnChange func(T) // User commits only, once per changed value, after updating state. }
SelectBox is a focusable dropdown that chooses a typed value. Highlighting and searching do not commit; Enter or an enabled row click commits. Escape, Tab, blur and outside clicks cancel. The existing Select function projects signals, so this widget uses the distinct name SelectBox.
func (SelectBox[T]) Build ¶ added in v0.20.0
func (s SelectBox[T]) Build(ctx BuildContext) Widget
Build derives the closed control and registers an anchored popup without mutating state. Keyboard focus remains on the control throughout a choice.
func (SelectBox[T]) CapturesKey ¶ added in v0.20.0
CapturesKey keeps ancestor character shortcuts out of search input and hints.
func (SelectBox[T]) GetContentDimensions ¶ added in v0.20.0
func (SelectBox[T]) IsFocusable ¶ added in v0.20.0
func (SelectBox[T]) Keybinds ¶ added in v0.20.0
Keybinds describes the actions available in the current popup state.
func (SelectBox[T]) OnBlur ¶ added in v0.20.0
func (s SelectBox[T]) OnBlur()
OnBlur cancels a pending choice without changing the committed value.
func (SelectBox[T]) OnClick ¶ added in v0.20.0
func (s SelectBox[T]) OnClick(event MouseEvent)
OnClick toggles the popup on a left click. Other buttons are ignored.
type SelectOption ¶ added in v0.20.0
type SelectOption[T comparable] struct { Label string Value T Disabled bool }
SelectOption is a labelled value in a SelectBox. Values should be stable, reflexive comparable keys; use scalar IDs for records containing maps or slices.
type SelectState ¶ added in v0.20.0
type SelectState[T comparable] struct { // contains filtered or unexported fields }
SelectState holds a committed value independently of an in-progress choice. Create it once with NewSelectState, outside Build, and retain it across builds.
func NewSelectState ¶ added in v0.20.0
func NewSelectState[T comparable]() *SelectState[T]
NewSelectState creates a select with no committed value.
func (*SelectState[T]) Clear ¶ added in v0.20.0
func (s *SelectState[T]) Clear()
Clear unsets the committed value and cancels any in-progress choice.
func (*SelectState[T]) SetValue ¶ added in v0.20.0
func (s *SelectState[T]) SetValue(value T)
SetValue sets a committed value and cancels any in-progress choice. It never invokes the widget's OnChange callback. Values absent from Options are retained.
func (*SelectState[T]) Value ¶ added in v0.20.0
func (s *SelectState[T]) Value() (T, bool)
Value returns the committed value and whether it is set. It subscribes the current reactive phase to changes. The zero value is a valid selection.
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
Link string `json:"l,omitempty"` // OSC 8 hyperlink URL
}
SerializedCell represents a cell that can be JSON serialized.
type Shimmer ¶ added in v0.20.0
type Shimmer struct {
State *ShimmerState // Required - drives the highlight
Base ColorProvider // Required - color away from the band; may be a Gradient
Highlight Color // Required - color at the band's center
BandWidth int // Width of the band in cells (default 8)
Path ShimmerPath // Route of the band (default ShimmerSweep)
}
Shimmer is a ColorProvider that blends a highlight band into a base color and moves it as its State runs. Use it anywhere a color is accepted:
state := NewShimmerState(0)
state.Start()
Text{Content: "Thinking...", Style: Style{ForegroundColor: Shimmer{
State: state, Base: theme.TextMuted, Highlight: theme.Text,
}}}
Style{Border: RoundedBorder(Shimmer{
State: state, Base: theme.Border, Highlight: theme.Accent, Path: ShimmerPerimeter,
})}
The highlight moves on repaint only: no rebuild or relayout.
type ShimmerPath ¶ added in v0.20.0
type ShimmerPath int
ShimmerPath is the route a Shimmer's highlight travels.
const ( // ShimmerSweep moves the highlight left to right. It enters fully off the // left edge and leaves fully off the right, so each cycle starts and ends // on plain base color. Suits text. ShimmerSweep ShimmerPath = iota // ShimmerPerimeter moves the highlight clockwise around the edge of the // region, wrapping seamlessly. Suits borders. ShimmerPerimeter )
type ShimmerState ¶ added in v0.20.0
type ShimmerState struct {
// contains filtered or unexported fields
}
ShimmerState drives the highlight of every Shimmer that uses it. Create with NewShimmerState and pass to a Shimmer.
func NewShimmerState ¶ added in v0.20.0
func NewShimmerState(period time.Duration) *ShimmerState
NewShimmerState creates a shimmer whose highlight completes its path once per period. A non-positive period defaults to 1.5s.
func (*ShimmerState) Advance ¶ added in v0.20.0
func (s *ShimmerState) Advance(dt time.Duration) bool
Advance implements the Animator interface.
func (*ShimmerState) IsRunning ¶ added in v0.20.0
func (s *ShimmerState) IsRunning() bool
IsRunning returns true if the shimmer is animating.
func (*ShimmerState) Start ¶ added in v0.20.0
func (s *ShimmerState) Start()
Start begins the shimmer. If called before the app is running, the shimmer starts when it is first painted.
func (*ShimmerState) Stop ¶ added in v0.20.0
func (s *ShimmerState) Stop()
Stop halts the shimmer and removes the highlight.
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 tracked render phase, the widget is automatically subscribed to future changes for that phase. 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. As a child of a Row or Column, though, a bare Spacer{} expands only along that container's main axis: a Spacer pushing buttons apart in a Row doesn't make the Row as tall as it can be.
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 LinkSpan ¶ added in v0.21.0
LinkSpan creates an underlined span that links to url, 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)
[link=URL] makes the text an OSC 8 terminal hyperlink, underlined in the theme's Link color unless the same tag names a foreground color:
ParseMarkup("See [link=https://example.com]the docs[/]", theme)
The URL ends at the first space or ], so percent-encode those characters.
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
// Link makes the span an OSC 8 terminal hyperlink to this URL. Terminals
// that support OSC 8 open it on their own link gesture (often Cmd or Ctrl
// and click); others show the text unchanged. A URL containing control
// characters is dropped.
Link string
}
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 self so spinner frames can update during paint without rebuilding the widget tree.
func (Spinner) BuildLayoutNode ¶ added in v0.5.0
func (s Spinner) BuildLayoutNode(ctx BuildContext) layout.LayoutNode
func (Spinner) ContentHeightHint ¶ added in v0.5.0
func (Spinner) ContentWidthHint ¶ added in v0.5.0
func (Spinner) GetContentDimensions ¶
GetContentDimensions returns the dimensions.
func (Spinner) Render ¶ added in v0.5.0
func (s Spinner) Render(ctx *RenderContext)
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.
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) BuildContainerLayoutNode ¶ added in v0.5.0
func (s SplitPane) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
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) Keybinds ¶
Keybinds returns the declarative keybindings for resizing the divider. A pane with DisableFocus has none: keys bubbling up from its children would otherwise move the divider.
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
MouseWheel func(MouseEvent) bool // Return true to consume wheel input before scrolling or bubbling
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) BuildContainerLayoutNode ¶ added in v0.5.0
func (s Stack) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
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) OnMouseWheel ¶ added in v0.17.0
func (s Stack) OnMouseWheel(event MouseEvent) bool
OnMouseWheel invokes the optional consumable wheel callback.
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
// Pointer sets the mouse pointer while hovering this widget or its children.
// The zero value inherits; PointerDefault explicitly stops inheritance.
Pointer PointerShape
// 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) BuildContainerLayoutNode ¶ added in v0.5.0
func (s Switcher) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
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 keyboard and drag reordering
DragShadow *FloatShadow // Optional shadow while dragging a tab
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
MouseWheel func(MouseEvent) bool // Return true to consume wheel input before scrolling or bubbling
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.
func (TabBar) OnMouseWheel ¶ added in v0.17.0
func (t TabBar) OnMouseWheel(event MouseEvent) bool
OnMouseWheel invokes the optional consumable wheel callback.
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) MoveTab ¶ added in v0.20.0
MoveTab moves a tab to a zero-based index without changing the active tab. It returns false for an unknown key, invalid index, or unchanged position.
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) SetLabel ¶
SetLabel updates the label of a tab by key. Setting an unknown key or the current label changes nothing, so it does not cancel an in-progress tab drag.
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 keyboard and drag reordering
DragShadow *FloatShadow // Optional shadow while dragging a tab
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 { Comparators map[string]func(T, T) int // Typed comparisons by unique column ID FrozenHeader bool // Own a bounded viewport and keep headers visible FrozenColumns int // Keep the first N columns visible during horizontal scrolling 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 or a row is double-clicked ActivateOnClick bool // Invoke OnSelect on a single left click instead of a double-click 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, shift+click or drag 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 moves the cursor to the clicked cell, extends the selection on shift+click in multi-select mode, and selects the row on double-click. Implements the MouseDownHandler interface.
func (Table[T]) OnMouseMove ¶ added in v0.11.0
func (t Table[T]) OnMouseMove(event MouseEvent)
OnMouseMove drags the cursor to the cell under the pointer while a press on a cell is held, extending the selection from the pressed cell in multi-select mode. Dragging past the top or bottom scrolls. Implements the MouseMoveHandler interface.
func (Table[T]) OnMouseUp ¶
func (t Table[T]) OnMouseUp(event MouseEvent)
OnMouseUp ends a drag begun on a cell. Implements the MouseUpHandler interface.
func (Table[T]) OnMouseWheel ¶ added in v0.20.0
func (t Table[T]) OnMouseWheel(event MouseEvent) bool
OnMouseWheel scrolls the table's own viewport when frozen panes are enabled.
type TableColumn ¶
type TableColumn struct {
ID string // Unique nonempty ID enables sorting and resizing
Resizable bool
MinWidth int // At least one cell for user resizing
MaxWidth int // Zero means unlimited
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 TableSort ¶ added in v0.20.0
type TableSort struct {
ColumnID string
Direction TableSortDirection
}
TableSort identifies a column and direction. None restores source/filter order.
type TableSortDirection ¶ added in v0.20.0
type TableSortDirection int
TableSortDirection specifies the ordering of a table view.
const ( TableSortNone TableSortDirection = iota TableSortAscending TableSortDescending )
type TableState ¶
type TableState[T any] struct { Rows AnySignal[[]T] // Reactive source rows; use SetRows for identity reconciliation CursorIndex Signal[int] // Source row index CursorColumn Signal[int] Selection AnySignal[map[int]struct{}] // Row/column/cell keys according to selection mode Sort Signal[TableSort] // View ordering; source rows remain unchanged ColumnWidths AnySignal[map[string]int] // User width overrides by unique column ID // 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 NewTableStateWithRowID ¶ added in v0.20.0
func NewTableStateWithRowID[T any](rows []T, rowID func(T) string) *TableState[T]
NewTableStateWithRowID preserves unique nonempty row identities across SetRows. The extractor must be pure and return stable IDs. Duplicate/empty identities cannot be preserved: their selection is dropped and their cursor is clamped.
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, along with the selection.
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. The cursor and selection stay on the same rows.
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. The cursor and selection stay on the same rows.
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. Selections on the removed row are dropped; other selections stay on their rows.
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. Selections on removed rows are dropped; other selections stay on their rows.
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 rows. Identity-aware states preserve unique records by ID; positional states clamp the cursor and drop selections past the new end.
func (*TableState[T]) ToggleSelection ¶
func (s *TableState[T]) ToggleSelection(index int)
ToggleSelection toggles the selection state of the row at the given index.
type Task ¶ added in v0.5.0
type Task[T any] struct { Phase Signal[TaskPhase] Running Signal[bool] Value AnySignal[T] Err AnySignal[error] // contains filtered or unexported fields }
Task runs one-shot background work and exposes its state through signals. Start cancels any existing run, executes fn in a goroutine, and applies the final task state on the UI thread when an app is running.
type TaskPhase ¶ added in v0.5.0
type TaskPhase int
TaskPhase describes the current lifecycle phase of a Task.
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
MouseWheel func(MouseEvent) bool // Return true to consume wheel input before scrolling or bubbling
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) OnMouseWheel ¶ added in v0.17.0
func (t Text) OnMouseWheel(event MouseEvent) bool
OnMouseWheel invokes the optional consumable wheel callback.
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
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
// ShowLineNumbers adds a fixed left gutter with 1-based, newline-delimited
// line numbers. Wrapped continuation rows are blank. The gutter stays put
// when unwrapped text scrolls horizontally.
ShowLineNumbers bool
// LineNumberStyle overrides the gutter's muted foreground and editor background.
LineNumberStyle SpanStyle
// SearchMatchStyle styles matches of State.SearchQuery. Zero uses a
// theme-derived default.
SearchMatchStyle SpanStyle
// SearchCurrentMatchStyle styles the match the selection covers, over the
// selection. Zero uses a theme-derived default.
SearchCurrentMatchStyle SpanStyle
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
// BeforeInput transforms typed text and Enter before insertion, after the
// read-only/insert-mode checks. It does not run for paste, deletion, undo,
// redo, or programmatic edits. Read context from State without mutating it.
// Returning the edit unchanged preserves normal typing/undo grouping.
// A changed edit is one undo step, including its final cursor and selection.
// A text-preserving edit only moves the caret, without history or OnChange.
// Ranges and caret positions are clamped to the document bounds.
BeforeInput func(TextAreaEdit) TextAreaEdit
// OnPaste is called with pasted text (line endings normalized to "\n")
// before it is inserted. Return true to consume the paste and skip
// inserting it.
OnPaste func(text string) bool
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)
// UndoKeys and RedoKeys undo and redo edits. Nil uses DefaultUndoKeys and
// DefaultRedoKeys; an empty slice turns the binding off.
UndoKeys []string
RedoKeys []string
}
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, and for the undo and redo keys, so ctrl+z undoes instead of suspending the app.
func (TextArea) ContentHeightHint ¶ added in v0.5.0
func (TextArea) ContentWidthHint ¶ added in v0.5.0
func (TextArea) CursorPosition ¶ added in v0.22.0
CursorPosition locates the hidden IME cursor. Render draws the text cursor.
func (TextArea) GetContentDimensions ¶
GetContentDimensions returns the width and height dimension preferences.
func (TextArea) HandlePaste ¶ added in v0.16.0
HandlePaste inserts pasted text at the cursor as a single edit, replacing any selection, newlines included. It is one undo step. OnPaste sees it first and can consume it. Tabs become four spaces. Implements the PasteHandler interface.
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) OnLayout ¶ added in v0.20.0
func (t TextArea) OnLayout(ctx BuildContext, metrics LayoutMetrics)
OnLayout reveals the cursor using the width that will be painted this frame.
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 TextAreaEdit ¶ added in v0.27.0
TextAreaEdit describes a replacement of [Start, End) in the current document. All positions are grapheme indexes, not byte or rune offsets. Cursor and SelectionAnchor refer to the document AFTER replacement; -1 means no anchor. BeforeInput receives the default edit and may return a modified copy.
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
// SearchQuery highlights every match of the query; "" means no search.
// Setting it directly only changes the highlights. SetSearch also selects
// the nearest match.
SearchQuery Signal[string]
SearchCaseSensitive Signal[bool]
// 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) CanRedo ¶ added in v0.21.0
func (s *TextAreaState) CanRedo() bool
CanRedo reports whether Redo would change the text.
func (*TextAreaState) CanUndo ¶ added in v0.21.0
func (s *TextAreaState) CanUndo() bool
CanUndo reports whether Undo would change the text.
func (*TextAreaState) ClearHistory ¶ added in v0.21.0
func (s *TextAreaState) ClearHistory()
ClearHistory forgets every undo and redo step.
func (*TextAreaState) ClearSearch ¶ added in v0.20.0
func (s *TextAreaState) ClearSearch()
ClearSearch removes the search and its highlights. Unlike SetSearch(""), it leaves the current match selected, for closing a search bar on the result.
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) NextMatch ¶ added in v0.20.0
func (s *TextAreaState) NextMatch()
NextMatch selects the match after the current one, or the first match at or after the cursor, wrapping around.
func (*TextAreaState) PreviousMatch ¶ added in v0.20.0
func (s *TextAreaState) PreviousMatch()
PreviousMatch selects the match before the current one, or the last match before the selection (or the cursor), wrapping around.
func (*TextAreaState) Redo ¶ added in v0.21.0
func (s *TextAreaState) Redo() bool
Redo reapplies the last undone step. It returns false when there is nothing to redo.
func (*TextAreaState) ReplaceSelection ¶
func (s *TextAreaState) ReplaceSelection(text string)
ReplaceSelection replaces any selected text with the given text, as one undoable step.
func (*TextAreaState) ReplaceText ¶ added in v0.21.0
func (s *TextAreaState) ReplaceText(text string, cursor int)
ReplaceText replaces the content as one undoable step and moves the cursor to cursor (a grapheme index, clamped to the new content).
func (*TextAreaState) SearchMatches ¶ added in v0.20.0
func (s *TextAreaState) SearchMatches() []TextRange
SearchMatches returns the ranges matching the search query. Called from Build, it subscribes to the content and the search inputs.
func (*TextAreaState) SearchPosition ¶ added in v0.20.0
func (s *TextAreaState) SearchPosition() (current, total int)
SearchPosition returns the 1-based index of the selected match (0 when the selection isn't a match) and the number of matches. Called from Build, it subscribes to the content, selection and search inputs.
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 text viewport. It accounts for scroll offset internally. contentWidth is the width available for text content (excluding the line-number gutter and scrollbar space).
func (*TextAreaState) SetSearch ¶ added in v0.20.0
func (s *TextAreaState) SetSearch(query string)
SetSearch highlights matches of query and selects the first match at or after the selection (or the cursor), wrapping to the first match. Extending the query therefore keeps the current match while it still matches. When nothing matches (including an empty query), a selection that was the previous match collapses to its start, so a half-typed query leaves no stray selection; any other selection stays.
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. It loads a new document, so it also clears the undo history; use ReplaceText for an edit the user can undo.
func (*TextAreaState) ToggleWrap ¶
func (s *TextAreaState) ToggleWrap()
ToggleWrap toggles between WrapNone and WrapSoft.
func (*TextAreaState) Undo ¶ added in v0.21.0
func (s *TextAreaState) Undo() bool
Undo reverts the last undo step, restoring the cursor and selection from before it. It returns false when there is nothing to undo.
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
// OnPaste is called with pasted text (line endings normalized to "\n")
// before it is inserted. Return true to consume the paste and skip
// inserting it, e.g. to import a pasted curl command.
OnPaste func(text string) bool
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)
// UndoKeys and RedoKeys undo and redo edits. Nil uses DefaultUndoKeys and
// DefaultRedoKeys; an empty slice turns the binding off.
UndoKeys []string
RedoKeys []string
}
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, and for the undo and redo keys, so ctrl+z undoes instead of suspending the app.
func (TextInput) ContentHeightHint ¶ added in v0.5.0
func (TextInput) ContentWidthHint ¶ added in v0.5.0
func (TextInput) CursorPosition ¶ added in v0.20.0
CursorPosition locates the hidden IME cursor. Render draws the text cursor.
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) HandlePaste ¶ added in v0.16.0
HandlePaste inserts pasted text at the cursor as a single edit, replacing any selection. OnPaste sees it first and can consume it. The input is one line, so a trailing newline is dropped and other newlines and tabs become spaces. It is one undo step. Implements the PasteHandler interface.
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) CanRedo ¶ added in v0.21.0
func (s *TextInputState) CanRedo() bool
CanRedo reports whether Redo would change the text.
func (*TextInputState) CanUndo ¶ added in v0.21.0
func (s *TextInputState) CanUndo() bool
CanUndo reports whether Undo would change the text.
func (*TextInputState) ClearHistory ¶ added in v0.21.0
func (s *TextInputState) ClearHistory()
ClearHistory forgets every undo and redo step.
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) Redo ¶ added in v0.21.0
func (s *TextInputState) Redo() bool
Redo reapplies the last undone step. It returns false when there is nothing to redo.
func (*TextInputState) ReplaceSelection ¶
func (s *TextInputState) ReplaceSelection(text string)
ReplaceSelection replaces any selected text with the given text, as one undoable step.
func (*TextInputState) ReplaceText ¶ added in v0.21.0
func (s *TextInputState) ReplaceText(text string, cursor int)
ReplaceText replaces the content as one undoable step and moves the cursor to cursor (a grapheme index, clamped to the new content).
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. The view scrolls back to the start, then as far as needed to show the cursor. It loads new text, so it also clears the undo history; use ReplaceText for an edit the user can undo.
func (*TextInputState) Undo ¶ added in v0.21.0
func (s *TextInputState) Undo() bool
Undo reverts the last undo step, restoring the cursor and selection from before it. It returns false when there is nothing to undo.
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
// Hover is laid beneath the item under the pointer in lists, tables, trees
// and tab bars. Keep it translucent so it tints whatever is beneath. If
// unset, it defaults to Text at DefaultHoverAlpha.
Hover Color
// Scrollbar colors
ScrollbarTrack Color
ScrollbarThumb Color
// Overlay/modal
Overlay Color // Semi-transparent backdrop
// Input-specific
Placeholder Color // Placeholder text
Cursor Color // Text cursor/caret; built-in themes use Selection's shade at full opacity
// 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 WithHover ¶ added in v0.14.0
func WithHover(c Color) ThemeOption
WithHover sets the Hover color, laid beneath the item under the pointer. Use a translucent 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 Toast ¶ added in v0.21.0
type Toast struct {
Title string // Optional bold heading
Message string // Body text; wraps to the toast's width
Severity ToastSeverity // Icon and color (default ToastInfo)
// Timeout is how long the toast stays once it is on screen. Zero uses the
// state's default; a negative value keeps it until it is dismissed.
Timeout time.Duration
}
Toast is one notification.
type ToastID ¶ added in v0.21.0
type ToastID uint64
ToastID identifies a toast returned by ToastState.Notify.
type ToastOptions ¶ added in v0.21.0
type ToastOptions struct {
MaxVisible int // Toasts on screen at once (default 3); the rest wait
Timeout time.Duration // Default timeout (default 4s)
}
ToastOptions configures a ToastState.
type ToastSeverity ¶ added in v0.21.0
type ToastSeverity int
ToastSeverity selects a toast's icon and theme color.
const ( ToastInfo ToastSeverity = iota ToastSuccess ToastWarning ToastError )
type ToastState ¶ added in v0.21.0
type ToastState struct {
// contains filtered or unexported fields
}
ToastState holds an app's notifications. Every method is safe to call from any goroutine. Create one with NewToastState, show it with a Toasts widget, and call Notify (or Info, Success, Warning, Error) to add a toast.
func NewToastState ¶ added in v0.21.0
func NewToastState(options ToastOptions) *ToastState
NewToastState creates an empty toast queue.
func (*ToastState) Dismiss ¶ added in v0.21.0
func (s *ToastState) Dismiss(id ToastID)
Dismiss removes a toast, shown or waiting. Unknown IDs are ignored.
func (*ToastState) Error ¶ added in v0.21.0
func (s *ToastState) Error(message string) ToastID
Error adds an error toast with a message.
func (*ToastState) Info ¶ added in v0.21.0
func (s *ToastState) Info(message string) ToastID
Info adds an info toast with a message.
func (*ToastState) Len ¶ added in v0.21.0
func (s *ToastState) Len() int
Len returns the number of toasts, shown or waiting.
func (*ToastState) Notify ¶ added in v0.21.0
func (s *ToastState) Notify(toast Toast) ToastID
Notify adds a toast and returns its ID. Its timeout starts once it is on screen, so toasts queued behind MaxVisible are not missed.
func (*ToastState) Success ¶ added in v0.21.0
func (s *ToastState) Success(message string) ToastID
Success adds a success toast with a message.
func (*ToastState) Warning ¶ added in v0.21.0
func (s *ToastState) Warning(message string) ToastID
Warning adds a warning toast with a message.
type Toasts ¶ added in v0.21.0
type Toasts struct {
ID string
State *ToastState // Required
// Position is the screen corner or edge the stack sits against (default
// FloatPositionBottomRight). FloatPositionCenter and FloatPositionAbsolute
// are treated as the default.
Position FloatPosition
Width int // Toast width in cells, including the border (default 40)
// RenderCard optionally replaces the entire card, including its border and
// padding. width is the resolved Width, including any border and padding;
// the callback is responsible for sizing its widget to fit. hovered reports
// whether the pointer is over the card. Nil uses the default tall-border card.
// It runs during Build and must be free of side effects. Custom cards retain
// click-to-dismiss and hover-to-pause behavior over their whole area.
RenderCard func(ctx BuildContext, toast Toast, width int, hovered bool) Widget
}
Toasts shows a ToastState's notifications stacked in a corner of the screen, above the rest of the app. Place it anywhere in the tree; it takes no space. Clicking a toast dismisses it, and hovering one holds its timeout.
toasts := NewToastState(ToastOptions{})
Stack{Children: []Widget{body, Toasts{State: toasts}}}
toasts.Success("Saved")
func (Toasts) Build ¶ added in v0.21.0
func (t Toasts) Build(ctx BuildContext) Widget
Build registers the overlay while there are toasts to show.
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) BuildContainerLayoutNode ¶ added in v0.5.0
func (t Tooltip) BuildContainerLayoutNode(ctx BuildContext, children []layout.LayoutNode) layout.LayoutNode
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) ActivateOnClick bool // Call OnSelect on a single left click on a node instead of a double-click 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, extends the selection on shift+click in multi-select mode, toggles expansion when the expand indicator is clicked, and selects the node on double-click elsewhere (or on a single click with ActivateOnClick). Implements the MouseDownHandler interface.
func (Tree[T]) OnMouseMove ¶ added in v0.11.0
func (t Tree[T]) OnMouseMove(event MouseEvent)
OnMouseMove drags the cursor to the node under the pointer while a press on a node is held, extending the selection from the pressed node in multi-select mode. Dragging past either end scrolls. Implements the MouseMoveHandler interface.
func (Tree[T]) OnMouseUp ¶ added in v0.11.0
func (t Tree[T]) OnMouseUp(event MouseEvent)
OnMouseUp ends a drag begun on a node. Implements the MouseUpHandler interface.
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]) ClearAnchor ¶ added in v0.20.0
func (s *TreeState[T]) ClearAnchor()
ClearAnchor removes the anchor point.
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 Validator ¶ added in v0.20.0
Validator checks a value and returns an error message, or an empty string. Validators must be pure and synchronous: reactive reads can run them repeatedly. Read cross-field dependencies with Get so their changes invalidate the view.
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 ThemeSwatch ¶ added in v0.11.0
ThemeSwatch returns a small preview chip for a registered theme: its background and surface colours fill the chip's left and right halves, with primary, secondary and accent dots drawn across them. Unknown themes render nothing.
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 ¶
type WidgetEntry struct {
Widget Widget
EventWidget Widget
ID string
// Bounds is the widget's border box in screen coordinates. Local mouse
// coordinates are relative to it. It can extend past what is drawn, for
// example when an ancestor has scrolled part of the widget out of view.
Bounds Rect
// Visible is the part of Bounds left after clipping by every ancestor and
// the screen. Only this area receives pointer events; it is empty for a
// widget scrolled entirely out of view.
Visible Rect
// Disabled is set for widgets inside a DisabledWhen subtree. They still
// take up their area for hit testing, but receive no presses or clicks.
Disabled bool
// contains filtered or unexported fields
}
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 visible at the point (x, y). Returns nil if no focusable widget contains the point.
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, visible Rect, disabled bool)
Record adds a widget to the registry with its bounds, visible area, optional ID and whether it is disabled.
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 visible at the point (x, y). Returns nil if no Scrollable contains the point.
func (*WidgetRegistry) ScrollablesAt ¶
func (r *WidgetRegistry) ScrollablesAt(x, y int) []*Scrollable
ScrollablesAt returns all Scrollable widgets visible at the point (x, y), ordered from innermost to outermost.
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 visible at the point (x, y). Returns nil if no widget contains the point. Since widgets are recorded in render order, the topmost (last rendered) widget at this position wins.
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
- app_session.go
- autocomplete.go
- bool_ptr.go
- breadcrumbs.go
- button.go
- checkbox.go
- clipboard.go
- clipboard_unix.go
- collection_pointer.go
- color.go
- command_palette.go
- command_palette_row.go
- command_palette_themes.go
- conditional.go
- context.go
- cursor.go
- cursor_blink.go
- dialog.go
- dimension.go
- directory_tree.go
- dock.go
- drag.go
- easing.go
- external.go
- field.go
- filepicker.go
- filepicker_build.go
- filter.go
- float_shadow.go
- floating.go
- focus.go
- focus_trap.go
- form.go
- frame_animation.go
- frame_scheduler.go
- hard_tabs_linux.go
- hard_tabs_unix.go
- headless_render.go
- highlight.go
- hover.go
- hyperlink.go
- image.go
- image_buffer.go
- image_detection.go
- image_diacritics.go
- image_kitty.go
- image_session.go
- image_sixel.go
- image_worker.go
- inline.go
- item_hover.go
- json_viewer.go
- jump.go
- keybind.go
- keybindbar.go
- keyformat.go
- label.go
- layout.go
- layout_helpers.go
- layout_metrics.go
- list.go
- log.go
- markdown.go
- markdown_layout.go
- markup.go
- menu.go
- mouse.go
- mouse_pixels.go
- navigation_paint_helpers.go
- nerd_font.go
- open_url.go
- panic.go
- passthrough.go
- paste.go
- pilot.go
- pilot_keys.go
- pointer.go
- presented_text.go
- print.go
- print_above.go
- progressbar.go
- registry.go
- render.go
- render_tree.go
- retained_renderer.go
- runtime_dispatch.go
- screen_mode.go
- scroll.go
- select_box.go
- shimmer.go
- signal.go
- signal_select.go
- snapshot.go
- snapshot_assert.go
- snapshot_box.go
- spacer.go
- sparkline.go
- spinner.go
- split_pane.go
- stack.go
- style.go
- switcher.go
- tab.go
- tab_drag.go
- table.go
- table_features.go
- table_layout.go
- table_viewport.go
- task.go
- terminal_output.go
- text.go
- text_area.go
- text_area_search.go
- text_history.go
- text_input.go
- theme.go
- toast.go
- tooltip.go
- tree.go
- widget.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
alignment-demo
command
|
|
|
animation-demo
command
|
|
|
ansi-to-svg
command
Command ansi-to-svg renders ANSI-styled terminal text (for example the output of `tmux capture-pane -p -e`) to an SVG using Terma's snapshot renderer.
|
Command ansi-to-svg renders ANSI-styled terminal text (for example the output of `tmux capture-pane -p -e`) to an SVG using Terma's snapshot renderer. |
|
api-client-example
command
|
|
|
async-task-example
command
|
|
|
auto-dimension-demo
command
|
|
|
autocomplete-example
command
|
|
|
border-example
command
|
|
|
checkbox-demo
command
Command checkbox-demo runs the Checkbox demo on its own.
|
Command checkbox-demo runs the Checkbox demo on its own. |
|
color-demo
command
|
|
|
command-palette-anchor-example
command
Command command-palette-anchor-example demonstrates a searchable tab picker attached to a changing tab bar, without measuring widget coordinates.
|
Command command-palette-anchor-example demonstrates a searchable tab picker attached to a changing tab bar, without measuring widget coordinates. |
|
command-palette-example
command
Command command-palette-example runs the Command Palette demo on its own.
|
Command command-palette-example runs the Command Palette demo on its own. |
|
debug_apps/column-layout-debug
command
|
|
|
debug_apps/key-event-debug
command
|
|
|
dialog-example
command
Command dialog-example runs the Dialog demo on its own.
|
Command dialog-example runs the Dialog demo on its own. |
|
directory-tree-example
command
|
|
|
disabled-button-demo
command
|
|
|
dock-example
command
|
|
|
dock-layout-demo
command
|
|
|
drag-drop-demo
command
|
|
|
example
command
|
|
|
fg-gradient-test
command
|
|
|
file-search-demo
command
|
|
|
filepicker-demo
command
Command filepicker-demo runs the same demo used by terma-demos.
|
Command filepicker-demo runs the same demo used by terma-demos. |
|
float-geometry-demo
command
float-geometry-demo builds a summary from current-frame anchor geometry.
|
float-geometry-demo builds a summary from current-frame anchor geometry. |
|
float-passthrough-demo
command
float-passthrough-demo puts a preview over a button and scrollable rows.
|
float-passthrough-demo puts a preview over a button and scrollable rows. |
|
floating-example
command
|
|
|
focus-example
command
|
|
|
focus-trap-demo
command
|
|
|
form-demo
command
Command form-demo exercises form validation and input state.
|
Command form-demo exercises form validation and input state. |
|
form-probe-demo
command
Command form-probe-demo exercises validation-driven focus through nested scroll views.
|
Command form-probe-demo exercises validation-driven focus through nested scroll views. |
|
gradient-border-example
command
|
|
|
gradient-demo
command
|
|
|
highlight-demo
command
|
|
|
hover-cause-demo
command
This demo keeps a keyboard-opened summary visible under a stationary pointer.
|
This demo keeps a keyboard-opened summary visible under a stationary pointer. |
|
hover-events-demo
command
|
|
|
hyperlink-demo
command
Command hyperlink-demo runs the Hyperlinks demo on its own.
|
Command hyperlink-demo runs the Hyperlinks demo on its own. |
|
image-demo
command
Image demo uses generated pixels; no files or network access are required.
|
Image demo uses generated pixels; no files or network access are required. |
|
inline-example
command
Command inline-example is a chat composer that runs inline, below the shell prompt, rather than taking over the screen.
|
Command inline-example is a chat composer that runs inline, below the shell prompt, rather than taking over the screen. |
|
internal/demokit
Package demokit holds what the widget demos share: the Demo interface they implement, the panel look they're drawn with, theme cycling, and Run for starting a demo on its own.
|
Package demokit holds what the widget demos share: the Demo interface they implement, the panel look they're drawn with, theme cycling, and Run for starting a demo on its own. |
|
internal/demos/checkboxdemo
Package checkboxdemo demonstrates Checkbox and CheckboxState.
|
Package checkboxdemo demonstrates Checkbox and CheckboxState. |
|
internal/demos/dialogdemo
Package dialogdemo demonstrates modal Dialogs: button variants, rich content, forms, and the different ways a dialog can be closed.
|
Package dialogdemo demonstrates modal Dialogs: button variants, rich content, forms, and the different ways a dialog can be closed. |
|
internal/demos/filepickerdemo
Package filepickerdemo demonstrates path selection using disposable fixtures.
|
Package filepickerdemo demonstrates path selection using disposable fixtures. |
|
internal/demos/formdemo
Package formdemo exercises validation, focus, dirty state and input adapters.
|
Package formdemo exercises validation, focus, dirty state and input adapters. |
|
internal/demos/hyperlinkdemo
Package hyperlinkdemo demonstrates OSC 8 terminal hyperlinks in markup, spans, Markdown and a scrolling list, and opening a link with OpenURL.
|
Package hyperlinkdemo demonstrates OSC 8 terminal hyperlinks in markup, spans, Markdown and a scrolling list, and opening a link with OpenURL. |
|
internal/demos/jsonviewerdemo
Package jsonviewerdemo demonstrates a standalone JSONViewer with live JSONPath filtering.
|
Package jsonviewerdemo demonstrates a standalone JSONViewer with live JSONPath filtering. |
|
internal/demos/jumpdemo
Package jumpdemo demonstrates jump mode: keyboard labels overlaid on the screen that move focus straight to what they label.
|
Package jumpdemo demonstrates jump mode: keyboard labels overlaid on the screen that move focus straight to what they label. |
|
internal/demos/listdemo
Package listdemo demonstrates List and the ListState modification APIs.
|
Package listdemo demonstrates List and the ListState modification APIs. |
|
internal/demos/markdowndemo
Package markdowndemo demonstrates rendered Markdown, safe link callbacks, whole-document copy, dynamic source replacement and incomplete fenced code.
|
Package markdowndemo demonstrates rendered Markdown, safe link callbacks, whole-document copy, dynamic source replacement and incomplete fenced code. |
|
internal/demos/menudemo
Package menudemo demonstrates Menu: dropdowns anchored to buttons, nested submenus, disabled items, dividers and a context menu.
|
Package menudemo demonstrates Menu: dropdowns anchored to buttons, nested submenus, disabled items, dividers and a context menu. |
|
internal/demos/palettedemo
Package palettedemo demonstrates CommandPalette: fuzzy search, nested levels, disabled items and live theme previews.
|
Package palettedemo demonstrates CommandPalette: fuzzy search, nested levels, disabled items and live theme previews. |
|
internal/demos/pilotdemo
Package pilotdemo is a small sign-up app shown next to the Pilot test that drives it (pilotdemo_test.go): typing, clicks, a background task, a spinner, a dialog and the clipboard, all checked without a terminal.
|
Package pilotdemo is a small sign-up app shown next to the Pilot test that drives it (pilotdemo_test.go): typing, clicks, a background task, a spinner, a dialog and the clipboard, all checked without a terminal. |
|
internal/demos/progressdemo
Package progressdemo demonstrates ProgressBar and Spinner.
|
Package progressdemo demonstrates ProgressBar and Spinner. |
|
internal/demos/scrolldemo
Package scrolldemo demonstrates Scrollable containers driven by ScrollState.
|
Package scrolldemo demonstrates Scrollable containers driven by ScrollState. |
|
internal/demos/selectdemo
Package selectdemo exercises committed choice, search, cancellation and edge states.
|
Package selectdemo exercises committed choice, search, cancellation and edge states. |
|
internal/demos/shimmerdemo
Package shimmerdemo demonstrates Shimmer: twenty animated highlights on text, borders and backgrounds.
|
Package shimmerdemo demonstrates Shimmer: twenty animated highlights on text, borders and backgrounds. |
|
internal/demos/splitpanedemo
Package splitpanedemo demonstrates nested SplitPanes with draggable, keyboard-movable dividers.
|
Package splitpanedemo demonstrates nested SplitPanes with draggable, keyboard-movable dividers. |
|
internal/demos/switcherdemo
Package switcherdemo demonstrates Switcher: one keyed child at a time, with each page's state kept outside it.
|
Package switcherdemo demonstrates Switcher: one keyed child at a time, with each page's state kept outside it. |
|
internal/demos/tabledemo
Package tabledemo demonstrates Table: variable-height cells, filtering with match highlighting, three selection modes and multi-select.
|
Package tabledemo demonstrates Table: variable-height cells, filtering with match highlighting, three selection modes and multi-select. |
|
internal/demos/tablefeaturesdemo
Package tablefeaturesdemo demonstrates sorting, resizing and frozen table panes.
|
Package tablefeaturesdemo demonstrates sorting, resizing and frozen table panes. |
|
internal/demos/tabsdemo
Package tabsdemo demonstrates TabView and the TabState behind it.
|
Package tabsdemo demonstrates TabView and the TabState behind it. |
|
internal/demos/textareademo
Package textareademo demonstrates the multi-line TextArea widget.
|
Package textareademo demonstrates the multi-line TextArea widget. |
|
internal/demos/textinputdemo
Package textinputdemo demonstrates the single-line TextInput widget.
|
Package textinputdemo demonstrates the single-line TextInput widget. |
|
internal/demos/toastdemo
Package toastdemo demonstrates toast notifications: each severity, sticky toasts, the waiting queue, corner placement, and toasts sent from a background goroutine.
|
Package toastdemo demonstrates toast notifications: each severity, sticky toasts, the waiting queue, corner placement, and toasts sent from a background goroutine. |
|
internal/demos/treedemo
Package treedemo demonstrates the Tree widget: lazy loading through OnExpand, filtering with match highlights, multi-select, and the OnSelect and OnCursorChange callbacks.
|
Package treedemo demonstrates the Tree widget: lazy loading through OnExpand, filtering with match highlights, multi-select, and the OnSelect and OnCursorChange callbacks. |
|
invalidation-demo
command
|
|
|
json-viewer-demo
command
Command json-viewer-demo runs the JSONViewer demo on its own.
|
Command json-viewer-demo runs the JSONViewer demo on its own. |
|
jump-example
command
Command jump-example runs the jump mode demo on its own.
|
Command jump-example runs the jump mode demo on its own. |
|
layout-test
command
|
|
|
list-demo
command
Command list-demo runs the List demo on its own.
|
Command list-demo runs the List demo on its own. |
|
list-example
command
|
|
|
long-list-example
command
Command long-list-example shows a List of 10,000 items in a Scrollable.
|
Command long-list-example shows a List of 10,000 items in a Scrollable. |
|
markdown-demo
command
Command markdown-demo runs the same demo used by terma-demos.
|
Command markdown-demo runs the same demo used by terma-demos. |
|
markup-demo
command
|
|
|
menu-example
command
Command menu-example runs the Menu demo on its own.
|
Command menu-example runs the Menu demo on its own. |
|
mouse-events-demo
command
|
|
|
nested-spacing
command
|
|
|
percent-demo
command
|
|
|
pilot-demo
command
Command pilot-demo runs the Pilot demo on its own: a sign-up app next to the test that drives it.
|
Command pilot-demo runs the Pilot demo on its own: a sign-up app next to the test that drives it. |
|
print-example
command
print-example demonstrates Terma's static printing API.
|
print-example demonstrates Terma's static printing API. |
|
progressbar-example
command
Command progressbar-example runs the Progress & Spinners demo on its own.
|
Command progressbar-example runs the Progress & Spinners demo on its own. |
|
reactivity-regressions
command
This demo reproduces the custom-row sizing and modal-backdrop regressions.
|
This demo reproduces the custom-row sizing and modal-backdrop regressions. |
|
scroll-debug
command
|
|
|
scroll-example
command
Command scroll-example runs the Scroll demo on its own.
|
Command scroll-example runs the Scroll demo on its own. |
|
scroll-overflow-test
command
|
|
|
select-demo
command
Command select-demo runs the same demo used by terma-demos.
|
Command select-demo runs the same demo used by terma-demos. |
|
shimmer-example
command
Command shimmer-example runs the Shimmer demo on its own.
|
Command shimmer-example runs the Shimmer demo on its own. |
|
simple-list-example
command
|
|
|
simple-table-example
command
|
|
|
simple-tree-example
command
|
|
|
slack-demo
command
|
|
|
snapshot-demo
command
|
|
|
spacer-example
command
|
|
|
spacing-example
command
|
|
|
sparkline-demo
command
|
|
|
split-pane-example
command
Command split-pane-example runs the SplitPane demo on its own.
|
Command split-pane-example runs the SplitPane demo on its own. |
|
stack-example
command
|
|
|
style-demo
command
|
|
|
switcher-example
command
Command switcher-example runs the Switcher demo on its own.
|
Command switcher-example runs the Switcher demo on its own. |
|
tab-example
command
Command tab-example runs the Tabs demo on its own.
|
Command tab-example runs the Tabs demo on its own. |
|
table-column-width-demo
command
|
|
|
table-demo
command
Command table-demo runs the Table demo on its own.
|
Command table-demo runs the Table demo on its own. |
|
table-example
command
|
|
|
table-features-demo
command
Command table-features-demo runs the same demo used by terma-demos.
|
Command table-features-demo runs the same demo used by terma-demos. |
|
table-inputs-demo
command
|
|
|
table-widgets-demo
command
|
|
|
terma-browser
command
terma-browser runs a local command in a browser terminal.
|
terma-browser runs a local command in a browser terminal. |
|
terma-demos
command
Command terma-demos brings every widget demo together in one app.
|
Command terma-demos brings every widget demo together in one app. |
|
terma-diff
command
|
|
|
text-area-demo
command
Command text-area-demo runs the TextArea demo on its own.
|
Command text-area-demo runs the TextArea demo on its own. |
|
text-input-example
command
Command text-input-example runs the TextInput demo on its own.
|
Command text-input-example runs the TextInput demo on its own. |
|
theme-demo
command
|
|
|
ticker-example
command
|
|
|
toast-example
command
Command toast-example runs the Toasts demo on its own.
|
Command toast-example runs the Toasts demo on its own. |
|
todo-app
command
|
|
|
tooltip-demo
command
|
|
|
tree-example
command
Command tree-example runs the Tree demo on its own.
|
Command tree-example runs the Tree demo on its own. |
|
tutorial/01-hello-world
command
|
|
|
tutorial/02-counter
command
|
|
|
tutorial/03-progress-bar
command
|
|
|
tutorial/04-animation
command
|
|
|
tutorial/05a-todo-list
command
|
|
|
tutorial/05b-todo-scrollable
command
|
|
|
tutorial/05c-todo-empty-state
command
|
|
|
tutorial/05d-todo-multiselect
command
|
|
|
wheel-tabs-demo
command
wheel-tabs-demo switches a one-row tab bar without a Scrollable wrapper.
|
wheel-tabs-demo switches a one-row tab bar without a Scrollable wrapper. |
|
widget-showcase
command
|
|
|
docs
|
|
|
minimal-examples/tabs-basic
command
|
|
|
minimal-examples/textinput-basic
command
|
|
|
minimal-examples/tree-basic
command
|
|
|
minimal-examples/widget-counter
command
|
|
|
minimal-examples/widget-start
command
|
|
|
widget-examples
command
|
|
|
internal
|
|
|
imagequant
Adapted from github.com/charmbracelet/x/ansi/sixel v0.11.3.
|
Adapted from github.com/charmbracelet/x/ansi/sixel v0.11.3. |
|
textutil
Package textutil contains text operations shared by layout and painting.
|
Package textutil contains text operations shared by layout and painting. |