layout

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package layout is a flexbox-style layout and composition engine for Flatte.

Every visual thing is a Node — an interface with two methods:

type Node interface {
    Size() (w, h Size)      // constraints for the parent's distribution
    Render(r Rect) string   // output at the solved rect
}

Concrete types embed NodeBase for shared geometry (W, H, Pad, Gap, Bordered) and add their own fields. Row distributes horizontally, Col vertically. Text carries a string. Widgets may expose Layout nodes; the primitive nodes implement both methods.

Solve returns geometry without painting. SolveAndCompose performs one shared top-down walk that distributes rectangles, records IDs, and paints leaves into a clipped cell buffer. Row and Col use that same compositor when they are rendered as nested nodes, so layout geometry and pixels cannot drift.

Index

Constants

View Source
const (
	PointsPerColumn = 8
	PointsPerLine   = 16
)

PointsPerColumn and PointsPerLine are the nominal terminal cell a terminal reads Points sizes at: the 13pt macOS monospace cell, rounded.

Variables

This section is empty.

Functions

func ClampScroll added in v0.2.0

func ClampScroll(offset, viewport, content int) int

ClampScroll clamps a scroll offset to [0, content-viewport]: the offset a Scroll whose window is viewport rows tall shows for content rows of child. The walk uses it, so an app clamping its own OffsetY with it agrees with what is painted. Negative heights count as zero.

func Overlay

func Overlay(base, layer string) string

Overlay draws layer centered over base as an ANSI-aware cell composite.

func OverlayAt added in v0.2.0

func OverlayAt(base, layer string, x, y int) string

OverlayAt draws layer over base with its top-left cell at (x, y), as an ANSI-aware cell composite (the canvas grows to hold the layer).

func OverlayOrigin

func OverlayOrigin(base, layer string) (x, y int)

OverlayOrigin is where Overlay places layer's top-left cell. Overlay calls this, so the two cannot drift apart.

func Solve

func Solve(root Node, width, height int) map[string]Rect

Solve returns the id→rect geometry for a tree without painting. It is the geometry-only mode of the shared walk (buf nil), so its rects are identical to the ones SolveAndCompose records while composing.

func SolveAndCompose

func SolveAndCompose(root Node, width, height int) (string, map[string]Rect)

SolveAndCompose walks the tree exactly once. It distributes rects top-down (the same math as Solve) and, in the same pass, paints each leaf's Render(rect) into a cell buffer at its absolute position, recording the rect of every node that carries an ID. It returns the composed frame string and the id→rect geometry map.

This is the single-pass alternative to calling Solve and Render separately: geometry and pixels come from one traversal and one distribution computation, so they cannot drift. Because leaves are painted at their solved coordinates and clipped to the buffer, a leaf that overflows its rect cannot corrupt the frame, and a leaf that under-fills simply reveals whatever a parent painted underneath — there is no "every leaf must fill its rect exactly" invariant.

Types

type Align added in v0.2.0

type Align int

Align is how a container places its children across its main axis: a Row's vertically, a Col's horizontally. A child with a Fixed or content size keeps it, and the rest of the space goes before it (AlignEnd), around it (AlignCenter), or after it (AlignStart). AlignStretch, the default, keeps Fixed sizes at the start and stretches the rest; a Grow child fills the space under every Align.

const (
	AlignStretch Align = iota
	AlignStart
	AlignCenter
	AlignEnd
)

type Backdrop added in v0.2.0

type Backdrop struct {
	Source  image.Image
	Blur    float64
	Opacity float64
}

Backdrop is a picture filling a box in a GUI: Source blurred by Blur points and drawn at Opacity (0 means 1). Sharp (Blur 0), it is cropped to cover the box; blurred, all of it is stretched to the box, so a large blur leaves every color of it as a soft wash.

type BorderKind added in v0.2.0

type BorderKind int

BorderKind is the line style of a Box border.

const (
	BorderNone BorderKind = iota
	BorderRounded
	BorderNormal
)

type Box added in v0.2.0

type Box struct {
	Border      BorderKind
	BorderColor color.Color
	Background  color.Color
	Selected    bool
	Round       bool
	Title       string
	TitleStyle  TextStyle
	Hover       color.Color
	// Interactive opts a named box into native hover feedback using the
	// theme's text tint when Hover is nil. Explicit Hover wins; transparent
	// disables the fill. Callers remove Interactive when the item is disabled.
	Interactive bool
	Backdrop    *Backdrop
	InsetY      float64
}

Box is a node's decoration. Nil colors mean the backend's default (no background; the terminal's default border color). Unknown border kinds draw as BorderRounded. Background is behind the node's content: leaf cells without a background of their own show it. Selected marks the node as the current selection: a GUI highlights it, while the terminal adds nothing (the app's markers and styles show selection there). Round asks a GUI to round a background's corners (a pill when the box is one line tall); the terminal cannot, and draws it square. Title labels a border: the terminal writes " Title " in TitleStyle into the top rule after its first rule glyph (cut to fit), and a GUI sets it in the top stroke, which breaks around it.

Hover is a GUI's fill while the pointer is over the node (it needs an ID), fading in and out, under its content and over its Background; the terminal draws nothing for it. Backdrop is a picture behind a GUI's box, under its Background — a translucent Background over it tints and dims it; the terminal draws only the Background.

InsetY draws all of that InsetY points inside the node's rect, top and bottom, in a GUI — a gap between the rows of a list without changing their layout (clicks in the gap still reach the node); terminals ignore it.

type BoxOp added in v0.2.0

type BoxOp struct {
	Rect, Clip PointRect
	Box        Box
	ID         string // the node's (for Box.Hover)
}

BoxOp draws a node's Box: its border within the Metrics.Border band around the inside of Rect, Box.Background behind the content, and a selection highlight when Box.Selected.

type Button added in v0.2.0

type Button struct {
	NodeBase
	Label                      string
	Style                      TextStyle
	Default, Disabled, Focused bool
	Icon                       IconName
	Plain                      bool
}

Button is a push button. The terminal draws "[ Label ]" in Style — bold when Default (the primary action), the label reversed when Focused, subtle when Disabled; a GUI draws a bezel, filled with the accent when Default (Style's Bg and Fg, when set, are a Default button's fill and label colors). On Auto axes it is its spelling wide and one line tall.

With an Icon, a GUI draws the icon's shape centered in the button instead of the Label, which stays its terminal spelling (as an Icon's Text): give it Points sizes for a square, which a Default button draws as a circle. Plain draws no bezel until the pointer is over it (a toolbar button), and in the terminal spaces instead of the brackets. An icon button's terminal brackets are tight ("[▶]"), so it fits a square of its own.

func (Button) Render added in v0.2.0

func (b Button) Render(r Rect) string

func (Button) Size added in v0.2.0

func (b Button) Size() (Size, Size)

type CellsOp added in v0.2.0

type CellsOp struct {
	Rect, Clip  PointRect
	Cols, Lines int
	Content     string
}

CellsOp draws terminal content — a Text leaf's ANSI string, a container's Chrome, or any node the scene does not know — as a grid of Cols×Lines monospace cells from the top-left of Rect. It is how every existing node still shows in a GUI.

type Col

type Col struct {
	NodeBase
	Children []Node
	Align    Align
}

Col lays children out vertically (main axis = height). Align places them horizontally.

func (Col) GetAlign added in v0.2.0

func (c Col) GetAlign() Align

func (Col) GetChildren

func (c Col) GetChildren() []Node

func (Col) GetGap

func (c Col) GetGap() int

func (Col) IsHorizontal

func (c Col) IsHorizontal() bool

func (Col) Render

func (c Col) Render(rect Rect) string

Render composes the column into a self-contained block sized to rect, delegating to the single walk via SolveAndCompose. See Row.Render for the rationale, including why the childless case stays on the direct path.

func (Col) Size

func (c Col) Size() (Size, Size)

Size declares the column's claims; see Row.Size.

type Composition added in v0.2.0

type Composition struct {
	Frame       string
	Rects       map[string]Rect
	Diagnostics []DuplicateIDDiagnostic
	// contains filtered or unexported fields
}

Composition is the result of one solve+paint walk: the composed frame, the id→rect geometry, duplicate-ID diagnostics, and the paint order needed to answer which node is on top at a cell.

func Compose added in v0.2.0

func Compose(root Node, width, height int) Composition

Compose is SolveAndCompose returning a Composition, which adds hit-testing in paint order to the frame, rects, and diagnostics.

func (Composition) CaretAt added in v0.2.0

func (c Composition) CaretAt(x, y int) (offset int, ok bool)

CaretAt reports, for cell (x, y) over an ID'd Input (the HitTest target), the byte offset into its Value of the caret position at that cell: the boundary before the grapheme there, or the end of the row past its text.

func (Composition) Cursor added in v0.2.0

func (c Composition) Cursor() (x, y int, ok bool)

Cursor reports where the hardware cursor belongs: at the caret of the topmost focused Input whose caret cell is visible. ok is false when no focused Input is painted.

func (Composition) HitTest added in v0.2.0

func (c Composition) HitTest(x, y int) (string, Rect)

HitTest returns the ID and solved rect of the topmost ID'd node containing cell (x, y): the last one painted, so children beat parents and overlays beat the base. The rect is that node's own (not the last-wins entry in Rects when IDs repeat), and whole even where a Scroll clips it, so x-rect.X and y-rect.Y are node-local coordinates. It returns "" and a zero Rect outside the frame, over an overlay area with no ID'd node, or where no ID'd node is painted.

type ControlKind added in v0.2.0

type ControlKind int

ControlKind is the control a ControlOp draws.

const (
	ControlButton ControlKind = iota
	ControlCheckbox
	ControlSwitch
	ControlRadio
	ControlSlider
)

type ControlOp added in v0.2.0

type ControlOp struct {
	ID                         string
	Kind                       ControlKind
	Rect, Clip                 PointRect
	Label                      string
	Style                      TextStyle
	Checked                    bool
	Value                      float64
	Fill                       color.Color
	Default, Disabled, Focused bool
	Icon                       IconName // a Button's icon (IconNone: its Label)
	Plain                      bool     // a Button without a bezel until hovered
	// Content is the padded label/indicator area. A zero value uses Rect.
	// Rect retains the outer bezel and full-size centered icon geometry.
	Content PointRect
}

ControlOp draws a control in Rect (its content box): a Button, a Toggle (checkbox, switch, or radio, with its Label), or a Slider at Value. A backend draws hover and press itself, for controls with an ID.

type DuplicateIDDiagnostic added in v0.2.0

type DuplicateIDDiagnostic struct {
	ID        string
	FirstRect Rect
	Duplicate Rect
}

DuplicateIDDiagnostic reports a repeated non-empty node ID in traversal order. The later node still wins in the returned rect map, preserving the historical behavior; diagnostics make accidental collisions observable without changing that behavior.

func SolveAndComposeWithDiagnostics added in v0.2.0

func SolveAndComposeWithDiagnostics(root Node, width, height int) (string, map[string]Rect, []DuplicateIDDiagnostic)

SolveAndComposeWithDiagnostics is SolveAndCompose with non-breaking duplicate-ID diagnostics. Empty IDs remain valid and are not reported.

func SolveWithDiagnostics added in v0.2.0

func SolveWithDiagnostics(root Node, width, height int) (map[string]Rect, []DuplicateIDDiagnostic)

SolveWithDiagnostics returns geometry and reports repeated non-empty IDs in deterministic traversal order. Duplicate IDs retain the existing last-node- wins map behavior; empty IDs are intentionally ignored.

type Icon added in v0.2.0

type Icon struct {
	NodeBase
	Name  IconName
	Text  string
	Style TextStyle
	// Animate moves the shape in a GUI (an equalizer's bars play); the
	// terminal shows it still.
	Animate bool
}

Icon is a small symbol with a terminal spelling: the terminal shows Text in Style, and a GUI draws the named shape in Style's color within the same columns, so rows line up in both. Unknown names draw Text.

func (Icon) Render added in v0.2.0

func (i Icon) Render(r Rect) string

func (Icon) Size added in v0.2.0

func (i Icon) Size() (Size, Size)

type IconName added in v0.2.0

type IconName int

IconName is a shape a GUI draws for an Icon. Names are shapes, not meanings: the app decides what a chevron or a dot stands for. The set grows when a sample needs a new shape.

const (
	// IconNone draws the Text, in a GUI too.
	IconNone IconName = iota
	IconChevronRight
	// IconDisclosureClosed and IconDisclosureOpen are the filled triangles
	// of a collapsed (▸) and expanded (▾) tree row.
	IconDisclosureClosed
	IconDisclosureOpen
	// IconDot is a filled circle (●), IconCircle an outlined one (○).
	IconDot
	IconCircle
	// IconBlank draws nothing in a GUI, keeping its columns: for terminal-only
	// decoration, such as the Powerline caps of a tab.
	IconBlank

	IconCheck   // ✓
	IconClose   // ✕
	IconPlus    // +
	IconMinus   // −
	IconSearch  // a magnifying glass
	IconGear    // ⚙
	IconInfo    // ⓘ, an i in a circle
	IconWarning // ⚠, an ! in a triangle
	IconError   // an ✕ in a circle
	IconArrowUp
	IconArrowDown
	IconArrowLeft
	IconArrowRight
	IconChevronLeft
	IconChevronUp
	IconChevronDown
	IconEllipsis // …
	IconFolder
	IconFile
	// Media and app shapes: play (▶), pause (⏸), previous and next track
	// (⏮ ⏭), shuffle (⇄), repeat (↻), a speaker (🔈), a house (⌂), and a
	// heart filled (♥) and outlined (♡).
	IconPlay
	IconPause
	IconPrevious
	IconNext
	IconShuffle
	IconRepeat
	IconSpeaker
	IconHome
	IconHeart
	IconHeartOutline
	// A clock face (🕒), and an equalizer's three bars (▁▃▅: something
	// playing).
	IconClock
	IconEqualizer
	// A library: two books standing and one leaning (a shelf of saved
	// things).
	IconLibrary
	// Repeat one: the repeat arrows (↻) around a small 1, for repeating a
	// single item.
	IconRepeatOne
)

type IconOp added in v0.2.0

type IconOp struct {
	Rect, Clip PointRect
	Name       IconName
	Text       string
	Style      TextStyle
	Animate    bool // the shape moves (Icon.Animate)
}

IconOp draws an Icon's named shape in Rect (the icon's content box), in Style's color; IconNone or an unknown name draws Text instead.

type Image added in v0.2.0

type Image struct {
	NodeBase
	Source image.Image
	Text   string
	Fit    ImageFit
}

Image is a picture. A GUI draws Source in its content box as Fit says, one image pixel to a point on Auto axes; a terminal shows Text in it, subtle and wrapped to its width (and sizes to Text on Auto axes), so give pictures a short description. A GUI reads Source when it first draws it: to change the picture, give a new image rather than changing its pixels. A Round Box rounds the picture's corners as it would a box's.

func (Image) Render added in v0.2.0

func (i Image) Render(r Rect) string

func (Image) Size added in v0.2.0

func (i Image) Size() (Size, Size)

type ImageFit added in v0.2.0

type ImageFit int

ImageFit is how an Image's picture fills its box in a GUI.

const (
	// ImageContain scales the picture to fit inside the box, keeping its
	// aspect ratio, centered.
	ImageContain ImageFit = iota
	// ImageCover scales it to cover the box, keeping its aspect ratio,
	// centered and cropped.
	ImageCover
	// ImageStretch scales it to the box exactly.
	ImageStretch
)

type ImageOp added in v0.2.0

type ImageOp struct {
	Rect, Clip PointRect
	Source     image.Image
	Fit        ImageFit
	Round      bool // corners rounded as a Round box's
}

ImageOp draws an Image's Source in Rect (its content box) as Fit says.

type Input added in v0.2.0

type Input struct {
	NodeBase
	Value       string
	Caret       int
	Placeholder string
	Focused     bool
	Style       TextStyle

	Multiline, Wrap  bool
	SelStart, SelEnd int
	SelectionStyle   TextStyle
	OffsetX, OffsetY int
	Bare             bool
	// Clearable shows a native clear affordance while Value is nonempty.
	// It emits MouseEvent.Clear for the app's field handler; terminal input
	// remains keyboard-editable and unchanged.
	Clearable bool
}

Input is a one-line text field: the value, the caret, and whether it has focus. It holds no editing state of its own — the app's widget (for example flatui.TextField, via its Layout method) owns the value and caret, and Input shows them. Backends draw it as a native-feeling field; the terminal draws the text and places the hardware cursor at the caret of the topmost focused Input (see Composition.Cursor).

Caret is a byte offset into Value; it is clamped into range and backed off to the start of a rune. A focused Input scrolls horizontally to keep the caret visible. When Value is empty the Placeholder shows in TextSubtle.

On Auto axes an Input fills the available width and is one line tall.

A Bare Input draws no field of its own in a GUI — no fill, no outline, no focus ring — only its text and caret, so it can sit inside a box the app draws (a search field with an icon and a clear button, say); the app shows focus on that box. The terminal draws an Input bare either way.

A Multiline Input is a text area (flatui.Textarea, via its Layout method, fills one in): "\n" breaks lines, Wrap soft-wraps them at the field's width, and its Auto height grows. Its selection runs from byte SelStart to SelEnd (either order; equal: none) and shows in SelectionStyle in the terminal (zero: reverse video) and as a native highlight in a GUI. OffsetX and OffsetY are the widget's scroll — the first visible display column, and the first visible line (visual row when wrapping) — clamped so the caret stays visible.

func (Input) Render added in v0.2.0

func (in Input) Render(r Rect) string

func (Input) Size added in v0.2.0

func (in Input) Size() (Size, Size)

type InputOp added in v0.2.0

type InputOp struct {
	ID          string
	Rect, Clip  PointRect
	Value       string
	Caret       int
	Placeholder string
	Focused     bool
	Style       TextStyle

	Multiline, Wrap  bool
	SelStart, SelEnd int
	OffsetY          int
	Bare             bool // no field chrome: the text and caret only
	Clearable        bool // native clear affordance; edit is delivered to the app
	// Field is the outer field bezel; Rect remains its text/caret area.
	// A zero Field uses Rect, for backends without component padding.
	Field PointRect
}

InputOp draws a text field in Rect (the input's content box). Caret is a byte offset into Value; a focused field shows it and receives text input. Scrolling a long value to keep the caret visible is the backend's job. A Multiline field breaks lines at "\n" (and wraps them at its width when Wrap), highlights the bytes SelStart..SelEnd, and scrolls from line OffsetY (the app's, in terminal rows: a hint) as little as keeps the caret's line visible.

type Label added in v0.2.0

type Label struct {
	NodeBase
	Text       string
	Style      TextStyle
	Wrap       bool
	Runs       []Run
	Selectable bool
	// Truncate ends a line too long for the label's box in "…", in the
	// terminal and a GUI (instead of clipping it); not with Wrap. A Tooltip
	// can show the whole text.
	Truncate bool
	// HoverFg is the native foreground color while the pointer rests over
	// this named label. It colors the whole label, including Runs; nil keeps
	// the label's normal and per-run colors. Terminals ignore it.
	HoverFg color.Color
}

Label is a leaf of plain text with a semantic style. Text holds no escape sequences (use Text for pre-styled strings). Like Text, it auto-sizes to its content on Auto axes, and lines break only at "\n" — unless Wrap is set: then it also wraps by words at its width (a word wider than the width breaks), in cells in the terminal and in the font in a GUI. A wrapping Label fills the width on an Auto width, and its Auto height is its wrapped line count at the width it gets.

Runs makes it rich text: when set, the label's text is the runs' text in order, each in its own Style (a run with a zero Style takes the Label's), and Text is ignored. Runs wrap as one text, so a line can break inside a run or between two.

Selectable lets a GUI user select the text with the pointer and copy it (⌘C): the window draws the selection itself, and the app still gets the clicks. Terminals ignore it — their own selection copies any text.

func (Label) Render added in v0.2.0

func (l Label) Render(r Rect) string

func (Label) Size added in v0.2.0

func (l Label) Size() (Size, Size)

type LayerOp added in v0.2.0

type LayerOp struct{ Rect PointRect }

LayerOp starts a logical overlay layer. A native backend lets an immediately following root BoxOp paint its own surface, preserving the page outside rounded corners; undecorated overlays clear their rectangle. Input/tooltip barriers are independent of this painting behavior.

type Meter added in v0.2.0

type Meter struct {
	NodeBase
	Value       float64
	Fill, Track color.Color
}

Meter is a horizontal gauge filled to Value (0..1, clamped; NaN is empty). The terminal draws round(Value×width) cells of █ in Fill and the rest as ░ in Track; a GUI draws a native bar. Nil colors are the backend's default. On Auto axes it fills the available width and is one line tall.

func (Meter) Render added in v0.2.0

func (m Meter) Render(r Rect) string

func (Meter) Size added in v0.2.0

func (m Meter) Size() (Size, Size)

type MeterOp added in v0.2.0

type MeterOp struct {
	Rect, Clip  PointRect
	Value       float64
	Fill, Track color.Color
}

MeterOp draws a Meter's gauge in Rect (its content box) filled to Value (0..1); nil colors are the backend's default.

type Metrics added in v0.2.0

type Metrics struct {
	Column, Line float64
	Step         float64
	Border       float64
	MeasureText  func(text string, style TextStyle, maxWidth float64) (w, h float64)
	MeasureRuns  func(runs []Run, maxWidth float64) (w, h float64)
	// DefaultPadding supplies GUI component defaults: controls get 8pt
	// horizontally/4pt vertically; decorated Row/Col containers get 12pt.
	// Explicit Pad fields replace these defaults; NodeBase.NoPadding opts out.
	// The window host enables this; custom point backends may opt in.
	DefaultPadding bool
	// ControlHeight is the minimum Auto height of buttons, toggles, and
	// non-Bare single-line inputs, in points. Zero or negative means no
	// minimum; explicit H values, Bare inputs and text areas are unchanged.
	ControlHeight float64
}

Metrics sizes the layout vocabulary for a backend that lays out in points, such as a GUI: Fixed sizes are columns and lines, Pad and Gap are spacing steps, and Border is the space a border takes on each side (the backend draws its stroke within that band, as a terminal draws a border within a cell). MeasureText reports the size of a Label's text in the backend's font for its style, wrapped by words at maxWidth points when maxWidth > 0 (a wrapping Label); nil measures text as cells (one column per cell of width, one line per line). MeasureRuns does the same for a rich-text Label's runs (styles resolved), wrapped as one text; nil measures their text in the Label's style.

type Node

type Node interface {
	Size() (w, h Size)
	Render(r Rect) string
}

Node is the primitive layout contract. Implementations should keep the two methods separate:

  • Size declares layout intent for each axis. It may return caller-authored constraints from NodeBase (Auto, Fixed, Grow), or measured natural content as SizeContent. It must not depend on a final Rect, because the parent calls Size before it knows the child's allocation.

  • Render draws the node inside the already-solved Rect. It should fill, clip, wrap, border, or join content to fit that rect, but it should not choose its own position or size in the parent.

In other words: Size answers "what space do I need or want?", while Render answers "given this exact space, what string do I produce?".

Note on cross-axis geometry: a child whose cross-axis Size is not Fixed stretches to fill the parent's cross axis (SizeContent included), so the rect recorded for a one-line ID'd Text in a Row spans the row's full height. That is correct for painting and coarse hit-testing; pin the cross axis with Fixed when a hit target must be exactly content-sized.

type NodeBase

type NodeBase struct {
	W, H     Size
	Pad      int
	Gap      int
	Bordered bool
	Overlay  bool
	ID       string

	// PadTop/PadRight/PadBottom/PadLeft add per-side padding on top of the
	// symmetric Pad (and inside the border, when Bordered). Extracted after
	// two panes needed asymmetric insets: horizontal-only padding and
	// "no top pad, one-row bottom pad" cannot be said with Pad alone.
	PadTop, PadRight, PadBottom, PadLeft int

	// Chrome, when set on a container, paints the node's own decoration
	// (styled border, background, title) instead of the default Pad/Box
	// fill. It receives the node's full solved rect and is painted before
	// (under) the children. It does not change the layout inset: Pad and
	// the border still declare the space the chrome occupies, so children
	// are placed inside that inset regardless of what Chrome draws. Leaves
	// ignore it — a leaf's Render owns all of its pixels already. Chrome is
	// terminal-only; prefer Box where it can say what is needed.
	Chrome func(r Rect) string

	// Box is the node's semantic decoration: border kind and color, and
	// background. A terminal draws it with box-drawing cells, a GUI as a
	// stroked and filled rect. A border takes one cell of inset per side,
	// exactly like Bordered (which is shorthand for Box{Border:
	// BorderRounded}; Box.Border wins when both are set).
	Box Box

	// Tooltip is help text a GUI shows while the pointer rests on the node
	// (the innermost node with one); the terminal ignores it.
	Tooltip string

	// Anchor places an Overlay next to the node with this ID instead of
	// centered on the frame: just below it and left-aligned to it, above
	// it when there is no room below, kept inside the frame — for a
	// dropdown or a context menu. An anchor that is not laid out (or an
	// empty one) centers the overlay as usual.
	Anchor string

	// NoPadding disables a GUI host's default component padding. Explicit
	// Pad/PadTop/PadRight/PadBottom/PadLeft still apply. Terminals ignore it.
	NoPadding bool

	// ItemPadding gives a Row/Col the GUI's regular item insets (8pt
	// horizontal, 4pt vertical) when default padding is enabled. Explicit
	// Pad fields or NoPadding override it. Terminal geometry is unchanged.
	ItemPadding bool
}

NodeBase provides shared geometry for all concrete node types. Embed it and override Size/Render as needed.

func (NodeBase) GetID

func (n NodeBase) GetID() string

func (NodeBase) IsOverlay

func (n NodeBase) IsOverlay() bool

func (NodeBase) Size

func (n NodeBase) Size() (Size, Size)

type Op added in v0.2.0

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

Op is one drawing operation of a Scene, in paint order. The set is closed: a backend draws these ten and nothing else. Every op's Clip is the visible region (the frame narrowed by enclosing Scrolls); draw only inside it.

type PointRect added in v0.2.0

type PointRect struct{ X, Y, W, H float64 }

PointRect is a rect in points.

func (PointRect) Cells added in v0.2.0

func (r PointRect) Cells(m Metrics) Rect

Cells converts r to whole columns and lines under m, rounding each field down (a viewport n lines tall shows n whole lines). Apps that read geometry in cells — LayoutEvent rects, MouseEvent coordinates — get it this way from a points backend. Values just below a boundary because of floating-point noise count as the boundary.

type Rect

type Rect struct{ X, Y, W, H int }

func (Rect) Contains

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

func (Rect) Inset

func (r Rect) Inset(n int) Rect

func (Rect) Intersect

func (r Rect) Intersect(s Rect) Rect

Intersect returns the overlapping region of r and s. If they do not overlap, it returns a zero-area rect anchored at the clamped corner. It is used to clamp a child's solved rect to its parent's inner box, so distribution overflow (e.g. two Fixed(8) children in a 10-wide row) can never yield a rect that escapes the parent or the frame — hit-testing trusts these rects.

type Row

type Row struct {
	NodeBase
	Children []Node
	Align    Align
}

Row lays children out horizontally (main axis = width). Embed NodeBase for geometry. Children participate in distribution via their Size() constraints. Align places them vertically.

func (Row) GetAlign added in v0.2.0

func (r Row) GetAlign() Align

func (Row) GetChildren

func (r Row) GetChildren() []Node

Introspection for Solve and overlay pass.

func (Row) GetGap

func (r Row) GetGap() int

func (Row) IsHorizontal

func (r Row) IsHorizontal() bool

func (Row) Render

func (r Row) Render(rect Rect) string

Render composes the row into a self-contained block sized to rect. It delegates to the single walk via SolveAndCompose (using rect's dimensions at a local origin) so container distribution, chrome, clipping, and overlay compositing all follow one code path. Only the childless case takes the direct fillBox path — which also prevents the walk (whose leaf branch would otherwise Render a container) from recursing.

func (Row) Size

func (r Row) Size() (Size, Size)

Size declares the row's claims: explicit W/H as set, and on an Auto axis the measured content of its children (or Grow(1) when the only claim on that axis is a growing child).

type Run added in v0.2.0

type Run struct {
	Text  string
	Style TextStyle
}

Run is a span of a Label's text in a style of its own.

type Scene added in v0.2.0

type Scene struct {
	Ops   []Op
	Rects map[string]PointRect
	// contains filtered or unexported fields
}

Scene is a frame solved in points: its drawing operations, the rect of every ID'd node, and the paint-order hit list.

func LayoutScene added in v0.2.0

func LayoutScene(root Node, width, height float64, m Metrics) Scene

LayoutScene solves root in a width×height-point frame with m. It runs the same walk as Compose — distribution, clipping, overlays, hit order — in points instead of cells.

func (Scene) HitTest added in v0.2.0

func (s Scene) HitTest(x, y float64) (string, PointRect)

HitTest returns the ID and rect of the topmost ID'd node at (x, y), with the same rules as Composition.HitTest.

func (Scene) IDsAt added in v0.2.0

func (s Scene) IDsAt(x, y float64) []string

IDsAt returns the visible IDs at (x, y), innermost first. Unlike Rects, it respects Scroll clipping and stops at the topmost overlay layer, including an overlay area without an ID. Hosts use it to hover nested nodes together without highlighting content covered by a modal.

func (Scene) TooltipAt added in v0.2.0

func (s Scene) TooltipAt(x, y float64) string

TooltipAt is the tooltip of the innermost (last painted) node at (x, y) that has one, or "" — also under an overlay that has none of its own.

type Scroll added in v0.2.0

type Scroll struct {
	NodeBase
	OffsetY int
	Child   Node
}

Scroll shows Child through a window: the child is laid out at its natural height and the Scroll's inner box (inside Pad/Bordered) shows the rows starting at OffsetY. Painting and hit-testing are clipped to that window, so scrolled-out nodes are neither drawn nor hittable.

The offset is app state: the app owns OffsetY, changes it from wheel and key events, and keeps whatever must stay visible in view. The walk clamps it to [0, content-viewport] with ClampScroll; apps clamp their own copy the same way so that scrolling back from an overshoot responds immediately.

Geometry needs no extra API. Rects of nodes inside a Scroll are reported in frame coordinates shifted by the effective offset (rows above the window have negative Y), and the content size is the child's own rect: give the child an ID to read it. Overlays inside a Scroll stay centered on the frame.

The child's height comes from its Size: Fixed is honored exactly, measured Content fills at least the window (so wrapping a layout that fits in a Scroll changes nothing visible), and Grow/Auto is the window height. Width follows the usual cross-axis rule: Fixed pins, everything else stretches.

Leaves inside a Scroll render at their full solved size and are then clipped; leaves entirely outside the window are not rendered at all.

func (Scroll) GetChildren added in v0.2.0

func (s Scroll) GetChildren() []Node

GetChildren exposes the child to the overlay pass.

func (Scroll) IsHorizontal added in v0.2.0

func (s Scroll) IsHorizontal() bool

func (Scroll) Render added in v0.2.0

func (s Scroll) Render(rect Rect) string

Render composes the Scroll into a block sized to rect through the shared walk, like Row and Col.

func (Scroll) Size added in v0.2.0

func (s Scroll) Size() (Size, Size)

Size measures the child's width on an Auto width. An Auto height reports Grow(1): a Scroll exists to be smaller than its content, so measuring the content would defeat it.

type ScrollBar added in v0.2.0

type ScrollBar struct {
	NodeBase
	Offset, Visible, Total int
	Color                  color.Color
}

ScrollBar shows where a scrolled window is: Visible of Total rows of content are shown, starting at row Offset. The terminal draws a thumb of █ on a track of ░ in Color, one glyph per line, and blanks when the content fits; a GUI draws a native thin thumb and nothing when it fits. Nil Color is the backend's default. The app owns the numbers (a List's Offset, Height and Count; a Viewport's Offset, VisibleLines and TotalLines). On Auto axes it is one column wide and fills the height.

func (ScrollBar) OffsetAt added in v0.2.0

func (b ScrollBar) OffsetAt(y, height int) int

OffsetAt is the offset a press or drag at line y of the bar asks for, on a bar height lines tall (y and height as in its rect, so y is node-local): the one whose thumb is centered nearest y, so the top line scrolls to the start and the bottom line to the end. It is Offset unchanged when there is nothing to scroll.

func (ScrollBar) Render added in v0.2.0

func (b ScrollBar) Render(r Rect) string

func (ScrollBar) Size added in v0.2.0

func (b ScrollBar) Size() (Size, Size)

type ScrollBarOp added in v0.2.0

type ScrollBarOp struct {
	Rect, Clip    PointRect
	Start, Length float64
	Show          bool
	Color         color.Color
}

ScrollBarOp draws a ScrollBar's thumb in Rect (its content box): it starts Start of the way down the track and is Length of it long (both fractions of Rect's height). Show reports whether there is anything to scroll; when false, draw nothing. A nil Color is the backend's default.

type Size

type Size struct {
	Kind   SizeKind
	Value  int
	Weight float64
}

Size is a one-axis layout constraint. Callers normally set Auto, Fixed, or Grow through the constructors below. SizeContent is produced by Size methods after measuring natural content, preserving the distinction between "caller forced this size" (Fixed) and "this is the content's natural size" (Content).

Weight is normally the proportional share a Grow child takes of a container's leftover main-axis space. For overlays it has a second, intentional meaning (see resolveLayerSize): a Grow overlay with Weight>=1 fills the whole viewport, while Weight<1 sizes to that fraction of the viewport. This dual use lets a caller express both "modal that is 60% of the screen" (Grow(0.6)) and "full-screen layer" (Grow(1)) without a separate field.

func Auto

func Auto() Size

func Fixed

func Fixed(n int) Size

func Grow

func Grow(w float64) Size

func Points added in v0.2.0

func Points(n int) Size

type SizeKind

type SizeKind int
const (
	// SizeAuto is the default "no explicit claim" input. If a node can measure
	// natural content on an auto axis, its Size method should return
	// SizeContent. If it cannot, auto contributes zero on the parent's main
	// axis and stretches on the cross axis.
	SizeAuto SizeKind = iota

	// SizeFixed is an exact caller-specified cell count.
	SizeFixed

	// SizeGrow takes a weighted share of the parent's remaining main-axis
	// space after fixed/content children are allocated.
	SizeGrow

	// SizeContent is a measured natural size, not usually a caller-authored
	// mode. Text and containers return it when an auto axis can be measured
	// from content or children. It behaves like fixed on the parent's main
	// axis, while still stretching on the cross axis.
	SizeContent

	// SizePoints is an exact length in points, for layouts designed for a
	// window. A GUI lays it out exactly; a terminal reads it at a nominal
	// cell of PointsPerColumn × PointsPerLine, rounding up. Otherwise it
	// behaves like SizeFixed.
	SizePoints
)

type Slider added in v0.2.0

type Slider struct {
	NodeBase
	Value             float64
	Fill              color.Color
	Disabled, Focused bool
}

Slider is a value from 0 to 1 along a track: the terminal draws ━ up to a ● knob and ─ after it, across its width (the knob reversed when Focused); a GUI draws a native slider. Fill colors the filled part (nil: the default). On Auto axes it fills the width and is one line tall. Map a click or drag to a value with ValueAt.

func (Slider) Render added in v0.2.0

func (s Slider) Render(r Rect) string

func (Slider) Size added in v0.2.0

func (s Slider) Size() (Size, Size)

func (Slider) ValueAt added in v0.2.0

func (s Slider) ValueAt(x, width int) float64

ValueAt is the value a press or drag at column x of a slider width columns wide asks for (x and width as in its rect, so x is node-local): the first column is 0, the last 1.

type Spacer

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

Spacer fills remaining space. Grows on both axes.

func NewSpacer

func NewSpacer() *Spacer

func (*Spacer) Render

func (s *Spacer) Render(r Rect) string

Render fills r with the spacer's background: the WithBackground color, or else Box.Background. A spacer has no border or padding of its own.

func (*Spacer) WithBackground

func (s *Spacer) WithBackground(c color.Color) *Spacer

type Text

type Text struct {
	NodeBase
	String string
}

Text is a leaf carrying a pre-rendered string. Auto-sizes to the string's dimensions unless explicit W/H is set on the embedded NodeBase.

func (Text) Render

func (t Text) Render(r Rect) string

func (Text) Size

func (t Text) Size() (Size, Size)

type TextOp added in v0.2.0

type TextOp struct {
	Rect, Clip PointRect
	Text       string
	Style      TextStyle
	Wrap       bool
	Runs       []Run
	Selectable bool
	Truncate   bool // a line too long for Rect ends in "…" (not with Wrap)
	ID         string
	HoverFg    color.Color
}

TextOp draws a Label's text from the top-left of Rect (the label's content box), one line per "\n" — and, when Wrap, wrapped by words at Rect's width as MeasureText wraps it. For a rich-text Label, Runs holds its runs with their styles resolved (Text is their text, Style the Label's), wrapped as MeasureRuns wraps them. Selectable is the Label's: the backend lets the user select and copy the text.

type TextRole added in v0.2.0

type TextRole int

TextRole is what a piece of text is for. Backends map roles to their own look — the terminal to colors and emphasis, a GUI to font size and weight — so neither bakes the other's look into the app. The set is deliberately small; unknown roles read as TextBody.

const (
	TextBody TextRole = iota
	TextTitle
	TextSubtle
)

type TextStyle added in v0.2.0

type TextStyle struct {
	Role   TextRole
	Fg, Bg color.Color
	// Size is the font size in points (0: the role's size). A GUI sets the
	// text at it, and its lines are that much taller; terminals ignore it.
	Size float64
	// Leading is a line's height over its font's in a GUI (0: the theme's
	// line spacing): below it to set lines close, as a title over a
	// subtitle; terminals ignore it.
	Leading float64

	Bold, Italic, Underline, Strikethrough bool
}

TextStyle is a role plus optional overrides applied on top of it. Nil colors and false flags leave the role's look unchanged.

func (TextStyle) Render added in v0.2.0

func (s TextStyle) Render(text string) string

Render returns text styled for a terminal. It is the single definition of each role's terminal look.

type Toggle added in v0.2.0

type Toggle struct {
	NodeBase
	Kind                       ToggleKind
	Label                      string
	Style                      TextStyle
	Checked, Disabled, Focused bool
}

Toggle is an on/off control: a checkbox, a switch, or a radio button, with its label. The terminal draws the indicator then the label in Style (the indicator reversed when Focused, all subtle when Disabled); a GUI draws a native indicator. On Auto axes it is its spelling wide and one line tall.

func (Toggle) Render added in v0.2.0

func (t Toggle) Render(r Rect) string

func (Toggle) Size added in v0.2.0

func (t Toggle) Size() (Size, Size)

type ToggleKind added in v0.2.0

type ToggleKind int

ToggleKind is how a Toggle looks: they differ in look only.

const (
	// ToggleCheckbox is "[x] Label" / "[ ] Label".
	ToggleCheckbox ToggleKind = iota
	// ToggleSwitch is "[ ●] Label" (on) / "[○ ] Label" (off).
	ToggleSwitch
	// ToggleRadio is "(•) Label" / "( ) Label"; one-of-many is the app's.
	ToggleRadio
)

Jump to

Keyboard shortcuts

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