awtree

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: MIT Imports: 10 Imported by: 0

README

awtree

Structured element detection for terminal UIs. Takes a styled character grid and produces a labeled element map — the terminal equivalent of a browser's accessibility tree.

Install

go get github.com/Tom-De-Santa-FOSS/awtree

Usage

g := awtree.NewGrid(24, 80)
g.SetText(5, 10, "[Save]", awtree.DefaultColor, awtree.DefaultColor, awtree.AttrReverse)

elements := awtree.Detect(g)
fmt.Println(awtree.Serialize(elements))
// [1:btn*:"Save" 5,10 w6]

debugElements := awtree.Detect(g, awtree.WithDebug(true), awtree.WithMaxButtonLabelLen(32))
fmt.Println(awtree.SerializeJSON(debugElements))
// {"elements":[...],"tree":[...],"debug":{"config":...}}

Detection

Signal Detects
Box-drawing chars Panels, windows, dialogs
Reverse-video regions Focused/selected elements
Edge rows with distinct BG Status bars, menu bars
Bracketed text [Save] Buttons

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RuneWidth

func RuneWidth(r rune) int

RuneWidth reports the number of terminal cells needed to render r.

func Serialize

func Serialize(m *ElementMap) string

Serialize produces a compact, token-efficient text representation of an ElementMap for LLM consumption.

Format: [id:type:"label" row,col wxh] with * suffix on type for focused.

Example:

[1:panel:"File Browser" 0,0 40x20] [2:btn:"Save"* 12,35 6x1]

func SerializeJSON

func SerializeJSON(m *ElementMap) string

SerializeJSON produces a structured JSON representation of an ElementMap.

Types

type Attr

type Attr uint16

Attr is a bitmask of cell style attributes.

const (
	AttrBold          Attr = 1 << iota
	AttrFaint              //nolint:revive // consistent naming
	AttrItalic             //nolint:revive
	AttrUnderline          //nolint:revive
	AttrBlink              //nolint:revive
	AttrReverse            //nolint:revive
	AttrConceal            //nolint:revive
	AttrStrikethrough      //nolint:revive
)

type Cell

type Cell struct {
	Char         rune
	FG           Color
	BG           Color
	Attrs        Attr
	Width        int
	Continuation bool
}

Cell holds the character and style data for a single terminal cell.

type Color

type Color int32

Color represents a terminal color. Negative values mean "default".

const DefaultColor Color = -1

func PaletteColor

func PaletteColor(index int) Color

PaletteColor returns a palette-backed terminal color.

func RGBColor

func RGBColor(r, g, b uint8) Color

RGBColor packs a 24-bit true color value into a Color.

func (Color) IsRGB

func (c Color) IsRGB() bool

IsRGB reports whether c stores a 24-bit true color value.

func (Color) RGB

func (c Color) RGB() (uint8, uint8, uint8, bool)

RGB returns the unpacked RGB components for a true color.

type DebugEvent

type DebugEvent struct {
	Detector string `json:"detector"`
	Accepted bool   `json:"accepted"`
	Reason   string `json:"reason"`
	Label    string `json:"label,omitempty"`
	Bounds   *Rect  `json:"bounds,omitempty"`
}

type DebugInfo

type DebugInfo struct {
	Config DetectConfig `json:"config"`
	Events []DebugEvent `json:"events"`
}

type DetectConfig

type DetectConfig struct {
	MajorityThresholdPct int  `json:"majority_threshold_pct"`
	MaxButtonWidth       int  `json:"max_button_width"`
	MaxButtonLabelLen    int  `json:"max_button_label_len"`
	Debug                bool `json:"debug"`
}

DetectConfig controls configurable detection thresholds and diagnostics.

func DefaultDetectConfig

func DefaultDetectConfig() DetectConfig

DefaultDetectConfig returns the default detection settings.

type Element

type Element struct {
	ID            int         `json:"id"`
	Type          ElementType `json:"type"`
	Label         string      `json:"label"`
	Description   string      `json:"description,omitempty"`
	Bounds        Rect        `json:"bounds"`
	Focused       bool        `json:"focused"`
	Enabled       bool        `json:"enabled"`
	Checked       bool        `json:"checked"`
	Selected      bool        `json:"selected"`
	Visible       bool        `json:"visible"`
	Clipped       bool        `json:"clipped"`
	Role          string      `json:"role,omitempty"`
	Shortcut      string      `json:"shortcut,omitempty"`
	Ref           string      `json:"ref,omitempty"`
	VisibleBounds *Rect       `json:"visible_bounds,omitempty"`
	Children      []int       `json:"children,omitempty"` // IDs of contained elements; populated by BuildTree
}

Element represents a detected interactive or structural TUI element.

func BuildTree

func BuildTree(elements []Element) []Element

BuildTree populates Children by assigning each element to the tightest container that fully contains it.

type ElementMap

type ElementMap struct {
	Elements []Element  `json:"elements"`
	Viewport Rect       `json:"viewport"`
	Scrolled bool       `json:"scrolled"`
	Debug    *DebugInfo `json:"debug,omitempty"`
}

ElementMap is the result of detecting elements on a styled grid.

func Detect

func Detect(g *Grid, opts ...Option) *ElementMap

Detect analyzes a styled terminal grid and returns detected UI elements. Elements are assigned sequential IDs starting from 1.

func (*ElementMap) Query

func (m *ElementMap) Query(selector string) []Element

func (*ElementMap) QueryOne

func (m *ElementMap) QueryOne(selector string) *Element

type ElementType

type ElementType int

ElementType classifies a detected TUI element.

const (
	ElementPanel           ElementType = iota // Box-drawing bordered region
	ElementButton                             // Bracketed text like [Save], <OK>
	ElementInput                              // Cursor-adjacent editable field
	ElementMenuItem                           // Item in a vertical list/menu
	ElementStatusBar                          // Color-contiguous bar at screen edge
	ElementMenuBar                            // Horizontal menu at top
	ElementTab                                // Tab-bar label
	ElementText                               // Generic styled text region
	ElementCheckbox                           // Checkbox or radio button
	ElementProgressBar                        // Progress bar (block or ASCII)
	ElementTable                              // Tabular data with column separators
	ElementSeparator                          // Horizontal separator/divider line
	ElementDialog                             // Centered panel with buttons (modal)
	ElementScrollIndicator                    // Scroll arrows or block scrollbar
	ElementBreadcrumb                         // Path-like breadcrumb trail
)

func (ElementType) ShortString

func (t ElementType) ShortString() string

func (ElementType) String

func (t ElementType) String() string

type Grid

type Grid struct {
	Rows  int
	Cols  int
	Cells [][]Cell
}

Grid is a styled 2D character grid — the input to element detection.

func NewGrid

func NewGrid(rows, cols int) *Grid

NewGrid creates an empty grid with the given dimensions.

func (*Grid) At

func (g *Grid) At(row, col int) Cell

At returns the cell at (row, col). Returns a zero Cell if out of bounds.

func (*Grid) Set

func (g *Grid) Set(row, col int, c Cell)

Set writes a cell at (row, col). No-op if out of bounds.

func (*Grid) SetText

func (g *Grid) SetText(row, col int, text string, fg, bg Color, attrs Attr)

SetText writes a plain string at (row, col) with the given attributes.

type Option

type Option func(*DetectConfig)

Option configures Detect.

func WithDebug

func WithDebug(enabled bool) Option

WithDebug enables detection diagnostics on the returned ElementMap.

func WithMajorityThresholdPct

func WithMajorityThresholdPct(pct int) Option

WithMajorityThresholdPct sets the percentage threshold used for bar detection.

func WithMaxButtonLabelLen

func WithMaxButtonLabelLen(length int) Option

WithMaxButtonLabelLen sets the maximum allowed button label length.

func WithMaxButtonWidth

func WithMaxButtonWidth(width int) Option

WithMaxButtonWidth sets the maximum scan width for bracketed buttons.

type Rect

type Rect struct {
	Row    int `json:"row"`
	Col    int `json:"col"`
	Width  int `json:"width"`
	Height int `json:"height"`
}

Rect defines a rectangular region on the terminal grid.

Jump to

Keyboard shortcuts

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