ui

package
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 48 Imported by: 1 module, 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 ui builds user interfaces that Golet draws itself, on the GPU where it can, for windows that show no web page:

type counter struct{ n int }

func (s *counter) view(c *ui.Context) {
	ui.Column(c).Fill().Center().Gap(12).Children(func() {
		ui.Text(c, fmt.Sprint(s.n)).FontSize(40).Bold()
		if ui.PrimaryButton(c, "Increment").Clicked() {
			s.n++
		}
	})
}

golet.NewWindow(golet.WindowOptions{Title: "Counter", Content: ui.View(s.view)})

A view is a function of the app's state that builds the interface of one frame on the main thread; Golet calls it again after input, after Window.Update or Invalidate, and while something animates. Elements lay out their children with flexbox or in a Grid, take their colors from a Theme that follows the system's appearance, and answer questions about input, such as Clicked, where they are built. What an element keeps between frames (focus, scrolling, text being edited, animations) follows its position among its siblings, or its Key. Constructors return checked Element values that expire before the next build pass; one frame can contain several passes. Keep elements and custom parts out of app state and background goroutines. Handle provides persistent control identity for focus, commands and committed bounds; FocusBind connects desired focus to app data, and FocusedValue reads actual focus.

Views receive a stable *Context for their window, with its parent scope changing inside Children callbacks. Capture Services for persistent clipboard/URL callbacks and background redraws instead of storing Context. A control takes the user's input as its constructor returns, as Dear ImGui's and egui's widgets do: what it binds, a local copy too, holds the edit when the next statement reads it, and inline actions see the edits of the controls built before them. A container takes its input with its children, as the call that built it returns. Input follows the options of the frame the user acted on: Disabled, ReadOnly or Step set in a build govern the input of the frames after it. Changed and Submitted report input; OnClick, OnShortcut, OnChange and OnSubmit run after construction, before the rebuild. Input queries such as Clicked remain available.

Widgets take the theme's look, whose Spacing sizes them all. Each is built on a base without a look, such as ButtonBase, CheckboxBase, TabsBase or SelectBase, which handles the pointer, the keyboard, the focus and accessibility: style its elements for a design of your own.

Tester runs views in tests, without a window.

Index

Constants

View Source
const (
	KeyUnknown      = Key(platform.KeyUnknown)
	KeyEnter        = Key(platform.KeyEnter)
	KeyEscape       = Key(platform.KeyEscape)
	KeyBackspace    = Key(platform.KeyBackspace)
	KeyTab          = Key(platform.KeyTab)
	KeySpace        = Key(platform.KeySpace)
	KeyDelete       = Key(platform.KeyDelete)
	KeyInsert       = Key(platform.KeyInsert)
	KeyHome         = Key(platform.KeyHome)
	KeyEnd          = Key(platform.KeyEnd)
	KeyPageUp       = Key(platform.KeyPageUp)
	KeyPageDown     = Key(platform.KeyPageDown)
	KeyLeft         = Key(platform.KeyLeft)
	KeyRight        = Key(platform.KeyRight)
	KeyUp           = Key(platform.KeyUp)
	KeyDown         = Key(platform.KeyDown)
	KeyF1           = Key(platform.KeyF1)
	KeyF2           = Key(platform.KeyF2)
	KeyF3           = Key(platform.KeyF3)
	KeyF4           = Key(platform.KeyF4)
	KeyF5           = Key(platform.KeyF5)
	KeyF6           = Key(platform.KeyF6)
	KeyF7           = Key(platform.KeyF7)
	KeyF8           = Key(platform.KeyF8)
	KeyF9           = Key(platform.KeyF9)
	KeyF10          = Key(platform.KeyF10)
	KeyF11          = Key(platform.KeyF11)
	KeyF12          = Key(platform.KeyF12)
	KeyMinus        = Key(platform.KeyMinus)
	KeyEqual        = Key(platform.KeyEqual)
	KeyComma        = Key(platform.KeyComma)
	KeyPeriod       = Key(platform.KeyPeriod)
	KeySlash        = Key(platform.KeySlash)
	KeySemicolon    = Key(platform.KeySemicolon)
	KeyQuote        = Key(platform.KeyQuote)
	KeyBracketLeft  = Key(platform.KeyBracketLeft)
	KeyBracketRight = Key(platform.KeyBracketRight)
	KeyBackslash    = Key(platform.KeyBackslash)
	KeyBackquote    = Key(platform.KeyBackquote)
	KeyContextMenu  = Key(platform.KeyContextMenu)
	Key0            = Key(platform.Key0)
	Key1            = Key(platform.Key1)
	Key2            = Key(platform.Key2)
	Key3            = Key(platform.Key3)
	Key4            = Key(platform.Key4)
	Key5            = Key(platform.Key5)
	Key6            = Key(platform.Key6)
	Key7            = Key(platform.Key7)
	Key8            = Key(platform.Key8)
	Key9            = Key(platform.Key9)
	KeyA            = Key(platform.KeyA)
	KeyB            = Key(platform.KeyB)
	KeyC            = Key(platform.KeyC)
	KeyD            = Key(platform.KeyD)
	KeyE            = Key(platform.KeyE)
	KeyF            = Key(platform.KeyF)
	KeyG            = Key(platform.KeyG)
	KeyH            = Key(platform.KeyH)
	KeyI            = Key(platform.KeyI)
	KeyJ            = Key(platform.KeyJ)
	KeyK            = Key(platform.KeyK)
	KeyL            = Key(platform.KeyL)
	KeyM            = Key(platform.KeyM)
	KeyN            = Key(platform.KeyN)
	KeyO            = Key(platform.KeyO)
	KeyP            = Key(platform.KeyP)
	KeyQ            = Key(platform.KeyQ)
	KeyR            = Key(platform.KeyR)
	KeyS            = Key(platform.KeyS)
	KeyT            = Key(platform.KeyT)
	KeyU            = Key(platform.KeyU)
	KeyV            = Key(platform.KeyV)
	KeyW            = Key(platform.KeyW)
	KeyX            = Key(platform.KeyX)
	KeyY            = Key(platform.KeyY)
	KeyZ            = Key(platform.KeyZ)
	// KeyBack and KeyForward go back and forward in a history: the side
	// buttons of a mouse, and the keys of keyboards that have them. A
	// Router takes them.
	KeyBack    = Key(platform.KeyBack)
	KeyForward = Key(platform.KeyForward)
)

Keys.

View Source
const (
	Shift = Modifiers(platform.ModShift)
	Ctrl  = Modifiers(platform.ModCtrl)
	Alt   = Modifiers(platform.ModAlt)
	// Super is Command on macOS and the Windows key elsewhere.
	Super = Modifiers(platform.ModSuper)
)

Modifier keys.

View Source
const (
	CursorDefault    = Cursor(platform.CursorDefault)
	CursorPointer    = Cursor(platform.CursorPointer)
	CursorText       = Cursor(platform.CursorText)
	CursorMove       = Cursor(platform.CursorMove)
	CursorResizeEW   = Cursor(platform.CursorResizeEW)
	CursorResizeNS   = Cursor(platform.CursorResizeNS)
	CursorResizeNWSE = Cursor(platform.CursorResizeNWSE)
	CursorResizeNESW = Cursor(platform.CursorResizeNESW)
	CursorNotAllowed = Cursor(platform.CursorNotAllowed)
	CursorCrosshair  = Cursor(platform.CursorCrosshair)
	CursorGrab       = Cursor(platform.CursorGrab)
	CursorGrabbing   = Cursor(platform.CursorGrabbing)
	// CursorResizeN, E, S and W resize toward one side only, as at the
	// limit of a resize.
	CursorResizeN = Cursor(platform.CursorResizeN)
	CursorResizeE = Cursor(platform.CursorResizeE)
	CursorResizeS = Cursor(platform.CursorResizeS)
	CursorResizeW = Cursor(platform.CursorResizeW)
	// CursorResizeColumn and CursorResizeRow move the line between columns
	// or rows, as of a table or a split.
	CursorResizeColumn = Cursor(platform.CursorResizeColumn)
	CursorResizeRow    = Cursor(platform.CursorResizeRow)
	CursorVerticalText = Cursor(platform.CursorVerticalText)
	// CursorCopy and CursorAlias show that a drop copies or links what is
	// dragged.
	CursorCopy        = Cursor(platform.CursorCopy)
	CursorAlias       = Cursor(platform.CursorAlias)
	CursorContextMenu = Cursor(platform.CursorContextMenu)
	// CursorNone hides the pointer over the element, as over a video.
	CursorNone = Cursor(platform.CursorNone)
)

Pointer shapes.

View Source
const (
	TextDownstream = text.Downstream
	TextUpstream   = text.Upstream
)
View Source
const AlertDismissed = -2

AlertDismissed is what AlertDialog returns in the frame Escape closes the alert, choosing no button.

View Source
const RepeatForever = -1

RepeatForever repeats a sequence of Keyframes, or a Timeline, for as long as the view builds it (KeyframeOptions.Repeat, TimelineOptions.Repeat).

Variables

View Source
var (
	Smooth = Animation{Spring: SpringOptions{Duration: defaultSpringDuration}}
	Snappy = Animation{Spring: SpringOptions{Duration: defaultSpringDuration, Bounce: 0.15}}
	Bouncy = Animation{Spring: SpringOptions{Duration: defaultSpringDuration, Bounce: 0.3}}
)

Springs that settle without bouncing, with a little bounce, and with a visible one, as SwiftUI's of the same names; Smooth is the zero Animation's.

View Source
var Auto = float32(math.Inf(1))

Auto is an automatic margin, which takes the free space on its side, as in CSS: Margin(0, Auto) centers an element horizontally, and a Row's child with Margin(0, 0, 0, Auto) goes to the end with those after it.

View Source
var Cmd = func() Modifiers {
	if runtime.GOOS == "darwin" {
		return Super
	}
	return Ctrl
}()

Cmd is the modifier of the platform's shortcuts: Command on macOS, Control elsewhere, as in Cmd+C.

View Source
var Transparent = Color{}

Transparent is the color of nothing.

Functions

func AlertDialog

func AlertDialog(c *Context, open *bool, title string, message string, buttons ...string) int

AlertDialog shows an alert over the window while *open is true, as AppKit's: title, message, and buttons, the last of which is the default, in the accent color, with the focus, which Enter clicks. Escape closes the alert choosing no button, as canceling does, whatever the buttons say; a click outside the alert does nothing. It returns the index of the button clicked, in the frame it is, which closes the alert, AlertDismissed in the frame Escape closes it, and -1 otherwise. An alert that must be answered stays open by setting *open back to true on AlertDismissed. Assistive technology sees an alert named by title and described by message.

switch ui.AlertDialog(c, &app.asking, "Delete “Notes”?", "You can't undo this.", "Cancel", "Delete") {
case 1:
	app.delete()
}

func DataDragOver

func DataDragOver(e Element, options transfer.DropOptions) (transfer.Offer, bool)

DataDragOver makes e a native destination, as DropData does, and returns the advertised formats and operations while a matching drag is over it. Hover never invokes a data provider.

func DragOver

func DragOver[T any](e Element) (T, bool)

DragOver makes e take values of type T dragged within the window, as Drop does, and returns the value dragged over it, for showing it would take it.

func Drop

func Drop[T any](e Element) (T, bool)

Drop makes e take values of type T dragged within the window (Element.Drag) and returns the value dropped on it since the last frame.

if f, ok := ui.Drop[*File](folder); ok {
	app.move(f, dir)
}

func DropData

func DropData(e Element, options transfer.DropOptions) (transfer.Drop, bool)

DropData makes e take native transfers matching options, and reports a completed drop once, in the next frame. Decode custom formats explicitly from the returned Data. Empty Formats accepts nothing.

func EaseIn

func EaseIn(t float32) float32

EaseIn starts slowly (a cubic).

func EaseInOut

func EaseInOut(t float32) float32

EaseInOut starts and ends slowly (a cubic).

func EaseOut

func EaseOut(t float32) float32

EaseOut ends slowly (a cubic), as Animate moves.

func FocusedValue

func FocusedValue[T comparable](c *Context, field *T) T

FocusedValue returns actual focus from the committed window, independently of construction order or a pending FocusBind request. Zero means no member has focus. Use only on the UI thread.

func Linear

func Linear(t float32) float32

Linear moves at one speed.

func Local

func Local[T any](e Element, key any, init func() T) *T

Local returns state of type T that element e keeps from frame to frame, keyed by key among its states; init creates it the first time. Custom widgets keep what they need with it, on the element they create.

func Nearest

func Nearest(points ...Point) func(Point) Point

Nearest returns a Snap (DraggableOptions) that chooses the nearest of points, as the heights a sheet rests at:

Snap: ui.Nearest(ui.Point{}, ui.Point{Y: 200}, ui.Point{Y: 400}),

func Overlay

func Overlay(c *Context, fn func())

Overlay builds fn's elements above the rest of the window. Place them with Absolute, Left and Top, in DIPs relative to the window, or beside another element with AttachTo. Each, as it goes with the focus in it, gives the focus back to the element that had it as it came.

func Project

func Project(value, velocity float32) float32

Project returns where a value going at velocity, in its units per second, comes to rest as iOS's scroll views slow down (their normal deceleration rate): where a fling would carry it, to choose the target a spring takes it to (SpringOptions.Velocity).

func RegisterFont

func RegisterFont(data []byte, family string) error

RegisterFont adds a TrueType or OpenType font, or collection, that text can use with Font(family). An empty family keeps the font's own name.

func Render

func Render(view func(c *Context), width int, height int, scale float32) *image.RGBA

Render draws a frame of view in a window of width×height DIPs at scale device pixels per DIP, without a window: for snapshots and tests.

func Rubberband

func Rubberband(value, lo, hi, dimension float32) float32

Rubberband returns value held within lo and hi as iOS holds content dragged past its edges: beyond them, it goes less and less far, as on a rubber band, the less the larger dimension is (the size of what is dragged, along the drag).

func SafeToOpen

func SafeToOpen(url string) bool

SafeToOpen reports whether a link to url can open in the system when others wrote it, as a message, a language model's reply or a pasted document: an http, https or mailto address. Other schemes and paths open files and run programs (on Windows, "calc" and \\host\x.exe run), and javascript: runs script in a browser. Markdown views and the rich text editor open only these, unless the app opens links itself.

func UTF16ByteOffset

func UTF16ByteOffset(s string, index int) int

UTF16ByteOffset converts a native offset to a UTF-8 byte offset, rounding inside a surrogate pair down to the rune's beginning and clamping to s.

func UTF16Len

func UTF16Len(s string) int

UTF16Len returns the number of native text offsets in s.

Types

type Align

type Align uint8

Align positions children along an axis: Justify places them along the main axis (the direction of a Row or Column), AlignItems and AlignSelf across it.

const (
	// Start is the left of a row, the top of a column.
	Start Align = iota
	Center
	End
	// Stretch makes children as large as the container across its axis.
	Stretch
	// SpaceBetween, SpaceAround and SpaceEvenly spread children along the
	// main axis (Justify), or lines and grid tracks (AlignContent).
	SpaceBetween
	SpaceAround
	SpaceEvenly
	// Baseline lines up the first lines of text of the children of a row,
	// or of a grid's row, as a large price beside its small unit does
	// (AlignItems and AlignSelf). A child without text lines up its
	// bottom. Across a column it is Start.
	Baseline
)

type Anchor

type Anchor uint8

Anchor is a point of a box: a corner, the middle of a side, or the center.

const (
	AnchorTopLeft Anchor = iota
	AnchorTop
	AnchorTopRight
	AnchorLeft
	AnchorCenter
	AnchorRight
	AnchorBottomLeft
	AnchorBottom
	AnchorBottomRight
	AnchorTopStart
	AnchorStart
	AnchorBottomStart
	AnchorTopEnd
	AnchorEnd
	AnchorBottomEnd
)

Anchors, from left to right and top to bottom, then those on the side lines start and on the other: on the left and the right, or the right and the left of an element laid out right to left (Direction), as Flutter's AlignmentDirectional.

type Animation

type Animation struct {
	// Duration and Ease make a curve: Ease, EaseOut when nil, over
	// Duration.
	Duration time.Duration
	Ease     Easing
	// Spring is the spring of an Animation without a Duration.
	Spring SpringOptions
	// Delay is how long the value keeps going as it was after its target
	// changes, before it heads for the new one, as a list's rows do one
	// after another with Delay: time.Duration(i) * 30 * time.Millisecond.
	Delay time.Duration
}

Animation says how a value goes to a new target: along an easing curve for Duration, or, when Duration is zero, with a spring, which keeps the value's velocity when the target changes again on the way. The zero Animation is Smooth's spring:

x := card.AnimateTo("x", target, ui.Snappy)
fade := card.AnimateTo("fade", target, ui.Animation{Duration: 150 * time.Millisecond, Ease: ui.EaseInOut})

type Bitmap

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

Bitmap is an image to show with Image. Create it once: converting an image is not free.

func DecodeBitmap

func DecodeBitmap(data []byte) (*Bitmap, error)

DecodeBitmap decodes a PNG, JPEG, GIF (its first frame), WebP or BMP image. A JPEG photo shows upright, as its camera's EXIF orientation says.

func NewBitmap

func NewBitmap(img image.Image) *Bitmap

NewBitmap converts img.

func (*Bitmap) Pixelated

func (b *Bitmap) Pixelated() *Bitmap

Pixelated draws the bitmap's pixels as squares of their colors where it shows larger than its size, as pixel art draws, instead of blending neighbors smoothly. At whole multiples of its size, each pixel is a square of whole pixels of the screen; at others, squares of even sizes whose edges blend across one pixel of the screen, so that none is wider than the next and they glide when they move, as Ebitengine's FilterPixelated. Where it shows smaller, it is as smooth as any. It returns the bitmap.

func (*Bitmap) Size

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

Size returns the bitmap's size in pixels, which Image shows as DIPs.

func (*Bitmap) Update

func (b *Bitmap) Update(img image.Image)

Update shows img in place of the bitmap's picture, for one that changes as video does: the GPU keeps the bitmap's texture and uploads the new pixels, where a new Bitmap a frame would make a texture each, and keep each for a while. An *image.RGBA of rows 4×width bytes long from the origin, as image.NewRGBA makes, is taken as it is, without a copy: don't change its pixels until the next Update. Call it on the main thread, in the view or through Window.Update, which redraws the window to show it.

type BorderStyle

type BorderStyle uint8

BorderStyle is how a border draws.

const (
	BorderSolid BorderStyle = iota
	// BorderDashed draws each side in dashes about three times as long as
	// the side is wide, with a dash at both ends.
	BorderDashed
)

type Canvas

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

A Canvas is a bitmap that a painter draws, on the GPU where the window draws there: render to texture, as SkSurface, LÖVE's Canvas and raylib's RenderTexture2D. A view draws what seldom changes into one once, as a chart's grid or a map's ground, and shows it every frame for the price of an image; fades or tints a whole layer at once; or draws at a resolution of its own and shows it scaled, as pixel art scales up crisp (game.IntegerFit, in the game plugin).

It keeps what was last drawn into it until Draw draws it anew, and shows anywhere a bitmap does, through Bitmap.

func NewCanvas

func NewCanvas(w, h int) *Canvas

NewCanvas returns a canvas of w×h pixels, transparent until drawn.

func (*Canvas) Bitmap

func (cv *Canvas) Bitmap() *Bitmap

Bitmap returns the bitmap the canvas shows as, for Image, Painter.Image and Painter.ImageRegion; make it Pixelated to scale pixel art up crisp.

func (*Canvas) Draw

func (cv *Canvas) Draw(p *Painter, fn func(cp *Painter))

Draw draws the canvas anew, cleared to transparent, with what fn paints with cp in the canvas's pixels, during the frame p paints: a Draw callback's painter. What fn paints is what any painter paints: shapes, paths, text, images, parts of them, other canvases, under transforms and clips. Drawn, the canvas shows it from this frame on.

func (*Canvas) Size

func (cv *Canvas) Size() (w, h int)

Size returns the canvas's size in pixels, the units it is drawn in.

type CollapsibleParts

type CollapsibleParts struct {
	Trigger Element
	// contains filtered or unexported fields
}

CollapsibleParts contains checked handles for the parts of a custom widget.

func CollapsibleBase

func CollapsibleBase(c *Context, open *bool) CollapsibleParts

CollapsibleBase creates a collapsible without a look, open while *open: its Trigger, and below it the panel Panel builds. Collapsible is CollapsibleBase with the theme's look.

func (CollapsibleParts) Panel

func (_handle CollapsibleParts) Panel(fn func()) Element

Panel builds fn in the panel of the collapsible while it is open, and as it opens and closes, when the panel grows and shrinks with Progress, clipping what fn built. It returns the column holding what fn builds, to style, and nil while the collapsible is closed.

func (CollapsibleParts) Progress

func (_handle CollapsibleParts) Progress() float32

Progress returns how far the collapsible is open, from 0 closed to 1 open, moving between them as it opens and closes: draw its arrow from it. It moves at once where the desktop asks for less motion.

type Color

type Color struct {
	R, G, B, A uint8
	// contains filtered or unexported fields
}

Color is a color with straight (not premultiplied) alpha. R, G, B and A are its sRGB value. A Color from Oklch may lie outside the sRGB gamut and then also holds the wide color, which a window that draws a wide gamut (on a Mac whose screen shows one) shows in place of R, G and B; every other one shows them, the nearest sRGB color, found as CSS Color 4 does. Set R, G or B of such a color and the wide color is stale: make a new one instead.

func Hex

func Hex(s string) Color

Hex parses "#rgb", "#rgba", "#rrggbb" or "#rrggbbaa". It panics on other input, which is a mistake in the program.

func Oklch

func Oklch(l, c, h float32) Color

Oklch returns the color of CSS's oklch(l c h): lightness l from 0 to 1, chroma c (about 0 to 0.4) and hue h in degrees. Use Alpha for oklch(l c h / a).

A color Display P3 cannot show loses chroma, keeping its lightness and hue, as CSS does; a negative chroma is 0. A color outside the sRGB gamut is shown as it is by a window that draws a wide gamut, and as the nearest sRGB color by every other (see Color).

func RGB

func RGB(r, g, b uint8) Color

RGB returns an opaque color.

func RGBA

func RGBA(r, g, b uint8, alpha float32) Color

RGBA returns a color with alpha between 0 and 1.

func (Color) Alpha

func (c Color) Alpha(a float32) Color

Alpha returns the color with its alpha multiplied by a.

func (Color) Mix

func (c Color) Mix(o Color, t float32) Color

Mix returns the color t of the way from c to o.

func (Color) Over

func (c Color) Over(base Color) Color

Over returns c composited over the opaque color base.

func (Color) SRGB

func (c Color) SRGB() Color

SRGB returns c without its wide color: the nearest sRGB color, which a window that cannot draw a wide gamut shows.

type ColumnRange

type ColumnRange struct {
	// Cursor is the column the keys move from, where the border shows.
	Cursor string
	// Anchor is the column Shift extends the columns from.
	Anchor string
	// All chooses every column, as a click on a RowHeader cell does.
	All bool
}

ColumnRange is the columns of the block of cells a Table chooses (ListState.CellSelect), by column ID (TableColumn.ID, or Title).

type ComboboxParts

type ComboboxParts struct {
	Input Element
	// contains filtered or unexported fields
}

ComboboxParts contains checked handles for the parts of a custom widget.

func ComboboxBase

func ComboboxBase(c *Context, text *string) ComboboxParts

ComboboxBase creates a combobox without a look: a text input editing *text, whose popup of options, built with Popup and Item, opens below it as the user types, clicks it or presses Down. Up and Down move among the options, Enter or a click chooses one, which Chosen reports, and Escape, or the input losing the focus, closes the popup. Assistive technology sees a combo box, and follows the option the arrows are on.

cb := ui.ComboboxBase(c, &app.query)
cb.Input.Padding(6, 10).Border(1, gray).Label("Font")
cb.Popup(func(panel ui.Element) {
	panel.Padding(4).Background(white).Border(1, gray)
	for _, f := range fonts {
		item := cb.Item(f).Padding(6, 10)
		if item.Highlighted() {
			item.Background(blue).TextColor(white)
		}
		item.Children(func() { ui.Text(c, f) })
	}
})
if f, ok := cb.Chosen(); ok {
	app.font = f
}

Combobox, Autocomplete and TokenField are built on it.

func (ComboboxParts) Chosen

func (_handle ComboboxParts) Chosen() (string, bool)

Chosen returns the option the user chose in this frame, by a click or Enter: ask it after Popup, which takes the input of the options it built as it returns, so the choice can be handled in the same build pass.

func (ComboboxParts) Filtering

func (_handle ComboboxParts) Filtering() bool

Filtering reports whether the text is what the user typed since the popup opened, which the options should match; it is not when the popup opened by a click or Down, which shows them all.

func (ComboboxParts) Item

func (_handle ComboboxParts) Item(value string) Element

Item creates an option: a row that is Highlighted when the pointer or the arrows are on it, and that chooses value when clicked. The option the highlight moves to scrolls into view, once, so that the wheel scrolls on past it.

func (ComboboxParts) Open

func (_handle ComboboxParts) Open() bool

Open reports whether the popup shows.

func (ComboboxParts) Popup

func (_handle ComboboxParts) Popup(fn func(panel Element)) Element

Popup shows the popup below the input, at least as wide, while it is open: fn styles the panel and builds the options with Item. It returns the panel, or nil while closed or without options.

func (ComboboxParts) SetOpen

func (_handle ComboboxParts) SetOpen(o bool)

SetOpen opens or closes the popup.

type ConicGradient

type ConicGradient struct {
	Stops []GradientStop
	// Center is the point the colors turn around, in fractions of the
	// box's width and height from its top left corner; the zero Point is
	// its middle.
	Center Point
	// Angle is where the turn starts, in degrees clockwise from upwards, as
	// CSS's "from": 90 starts at the right, where SwiftUI's and Flutter's
	// start.
	Angle float32
	// Oklab mixes the colors in the Oklab color space, as LinearGradient's
	// does.
	Oklab bool
}

ConicGradient blends colors around a point, as CSS's conic-gradient() does (SwiftUI's AngularGradient, Flutter's SweepGradient): its stops at their places around a turn, clockwise from its angle.

e.ConicGradient(ui.ConicGradient{Stops: []ui.GradientStop{{red, 0}, {blue, 0.5}, {red, 1}}})

type Content

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

Content is a user interface for a window, the value of golet.WindowOptions.Content. Create it with View.

func View

func View(view func(c *Context)) *Content

View returns the content of a window whose user interface view builds, for golet.WindowOptions.Content:

golet.NewWindow(golet.WindowOptions{Title: "Counter", Content: ui.View(app.View)})

view runs on the main thread whenever the window needs a frame: after input, after Context.Invalidate or Window.Invalidate, and while something animates. A Content can serve several windows, each with its own state.

func (*Content) AttachContent

func (v *Content) AttachContent(conn *surface.Conn)

AttachContent connects the content to a window; package golet calls it.

type ContentTransition

type ContentTransition struct {
	Numeric, Down bool
	// Animation is how the content changes: a spring arriving in about
	// 350 ms without bouncing when nil.
	Animation *Animation
}

ContentTransition is how an element's content changes (Element ContentTransition): its text, its icon, or its picture.

By default, the old content fades out as the new fades in; an icon shrinks away as the new grows in, as SwiftUI's replace symbol effect. Numeric rolls the characters of a line of text that change, as a counter's digits, those that stay staying: the new come up from below, or, Down, from above, as SwiftUI's numericText.

type Context

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

Context is the window's stable UI context. Use it on the UI thread while building a view. Children share it and temporarily change its parent. Publish background results with Window.Update or Services.Invalidate.

func (*Context) AddToast

func (_handle *Context) AddToast(t Toast) string

AddToast shows t near the bottom of the window, as Toast does, and returns its ID, to close it with CloseToast:

id := c.AddToast(ui.Toast{Title: "Uploading", Timeout: -1})
// ...
c.CloseToast(id)

Adding a toast with the ID of one showing changes that toast, which shows anew. Toasts show with the theme's look, unless the view builds them with ToastViewportBase.

func (*Context) After

func (_handle *Context) After(d time.Duration)

After asks for another frame after d, for something that changes with time, such as a clock.

func (*Context) AnimationFrame

func (_handle *Context) AnimationFrame()

AnimationFrame asks for another frame as soon as the display can show it, for something moving. Call it in every frame while it moves. A drawing that moves while the layout stays asks with Painter.AnimationFrame instead, whose frames do not build the view.

func (*Context) Announce

func (_handle *Context) Announce(text string)

Announce asks screen readers to read text out once, after what they are reading, for news the keyboard focus does not bring, as a search done or a file saved: a Router announces the title of a page it shows, and a toast its text. It does nothing while no assistive technology reads the window.

func (*Context) CloseToast

func (_handle *Context) CloseToast(id string)

CloseToast closes the toast with id, or every toast when id is empty, and runs their OnClose.

func (*Context) Direction

func (_handle *Context) Direction() Direction

Direction returns the direction of the elements built now: that of the element they go in. Widgets of an app's own read it to draw what points along the line, as an arrow forward:

forward := "M5 2 11 8 5 14"
if c.Direction() == ui.RightToLeft {
	forward = "M11 2 5 8 11 14"
}

func (*Context) DisableAnimations

func (_handle *Context) DisableAnimations()

DisableAnimations makes the values that animate in this frame (AnimateTo, Animate, Spring), the element transitions and the pages of routers go to their targets at once, as SwiftUI's disablesAnimations: for a change that should not show as motion, as restoring a window's state or jumping to a search result. Call it before building what changes. Keyframes and timelines, which play on their own rather than towards a target, go on as they were: Seek a Timeline to jump it.

func (*Context) FocusWithin

func (c *Context) FocusWithin(ref Handle) bool

func (*Context) Focused

func (c *Context) Focused(ref Handle) bool

func (*Context) Invalidate

func (c *Context) Invalidate()

Invalidate requests a frame from any goroutine.

func (*Context) Key

func (c *Context) Key(key any) *Context

Key assigns the identity of the next control before its state is read. A compound widget consumes the key for its outermost element.

func (*Context) Locale

func (_handle *Context) Locale() string

Locale returns the language the app shows (golet.App.Locale), a BCP 47 tag such as "en" or "zh-Hans", for what the view says in it. Text is in it unless an element says otherwise (Element.Lang). A frame follows its changes, as App.SetLocale makes them.

func (*Context) MeasureText

func (_handle *Context) MeasureText(width float32, spans ...Span) (float32, float32)

MeasureText returns the size spans of text take as Painter.RichText draws them, wrapping lines at width DIPs (none for 0), to lay out what depends on it while building.

func (*Context) Modifiers

func (_handle *Context) Modifiers() Modifiers

Modifiers returns the modifier keys held now, as the last key, pointer or modifier event said: a view showing each row's shortcut while Cmd is held reads it, and draws again as it changes.

func (*Context) Now

func (_handle *Context) Now() time.Time

Now returns the time the frame started, for animations.

func (*Context) OnShortcut

func (c *Context) OnShortcut(mods Modifiers, key Key, fn func())

OnShortcut declares a handler in the current context's parent scope.

func (*Context) OpenURL

func (_handle *Context) OpenURL(url string)

OpenURL opens a URL in the default browser, or the app registered for its scheme, as a Link does. It returns at once; OpenURLThen tells what came of it.

func (*Context) OpenURLThen

func (_handle *Context) OpenURLThen(url string, done func(err error))

OpenURLThen opens a URL as OpenURL does, and done, unless nil, gets what came of it in a while, before a frame builds anew with what it changed: an error when no app could open the URL.

c.OpenURLThen(url, func(err error) {
	if err != nil {
		app.failed = url
	}
})

func (*Context) Preferences

func (_handle *Context) Preferences() Preferences

Preferences returns the settings of the desktop that controls follow. A frame follows their changes.

func (*Context) ReadClipboard

func (_handle *Context) ReadClipboard() string

ReadClipboard returns the text on the clipboard, and WriteClipboard puts text there, for widgets that copy and paste themselves. Call them on the main thread: in the view, or in an input handler.

func (*Context) Region

func (_handle *Context) Region() i18n.Region

Region returns the user's regional formats (golet.App.Region): the locale of the formats, the first day of the week and the hour cycle, which dates and times follow. A frame follows their changes.

func (*Context) Resolve

func (c *Context) Resolve(ref Handle) Element

Resolve returns this pass's element. Focus queries do not need Resolve.

func (*Context) Root

func (_handle *Context) Root() Element

Root returns the element holding the window's content: a column the size of the window.

func (*Context) Router

func (_handle *Context) Router() *Router

isPath reports whether a link's target is a path within the app, as "/notes/42", "edit" or "?tab=info", rather than a URL with a scheme. Router returns the router whose page is being built, which a Link to a path without a scheme goes through, or nil outside one.

func (*Context) Services

func (c *Context) Services() Services

Services returns the persistent services of this frame's window.

func (*Context) SetTheme

func (_handle *Context) SetTheme(t *Theme)

SetTheme makes the frame use t, for the window's root and the widgets created after the call.

func (*Context) Shortcut

func (_handle *Context) Shortcut(mods Modifiers, key Key) bool

Shortcut reports whether the key with exactly the modifiers mods was pressed, wherever the keyboard focus is, unless a focused element handled it first: a focused button or link takes Enter and Space, and a check box, switch or radio button Space, so that Enter can press a dialog's default button.

func (*Context) Size

func (_handle *Context) Size() (float32, float32)

Size returns the size of the window's content in DIPs.

func (*Context) Theme

func (_handle *Context) Theme() *Theme

Theme returns the theme of the frame: the light or dark theme following the system's appearance, unless SetTheme replaced it.

func (*Context) TitleBar

func (_handle *Context) TitleBar() TitleBar

TitleBar returns the room the window controls take in a window with a hidden title bar (golet.WindowOptions.TitleBarStyle), whose view draws the title bar under them: the traffic lights on macOS, the window buttons on Linux and Windows. It is zero in other windows and in full screen, where the controls hide. Keep clear of the controls, and let the title bar drag the window:

bar := c.TitleBar()
ui.Row(c).Height(max(bar.Height, 32)).Padding(0, bar.Right, 0, bar.Left).DragWindow()

func (*Context) Toast

func (_handle *Context) Toast(message string)

Toast shows message near the bottom of the window for a few seconds, as the outcome of what the user just did:

if ui.Button(c, "Save").Clicked() {
	app.save()
	c.Toast("Saved")
}

A message already showing shows anew; others stack above it, three at most. It shows for as long as the pointer rests on it. Screen readers read it out. It is AddToast with message as the ID and the title.

func (*Context) ToastAction

func (_handle *Context) ToastAction(message string, label string, action func())

ToastAction shows message as Toast does, for longer, with a button of label that runs action, as Undo after deleting, and closes the toast; Tab reaches the button. action runs on the main thread, as the view does, which builds the frame again after it.

app.trash(note)
c.ToastAction("Note deleted", "Undo", func() { app.restore(note) })

func (*Context) Valid

func (c *Context) Valid() bool

Valid reports whether this context is building a view.

func (*Context) Vibrancy

func (_handle *Context) Vibrancy() bool

Vibrancy reports whether the window shows its material (golet.WindowOptions.Vibrancy) wherever the view draws no background: on macOS, and on Windows 11 22H2 and later in a window created with one. Elsewhere, what the view leaves transparent shows no material: draw a background there instead. The root draws the theme's background unless told otherwise; a sidebar over the material, beside opaque content:

if c.Vibrancy() {
	c.Root().Background(ui.Transparent)
}
ui.Row(c).Fill().AlignItems(ui.Stretch).Children(func() {
	sidebar := ui.Column(c).Width(240)
	if !c.Vibrancy() {
		sidebar.Background(c.Theme().Surface)
	}
	sidebar.Children(func() { app.sidebar(c) })
	ui.Column(c).Grow(1).Background(c.Theme().Background).Children(func() { app.content(c) })
})

func (*Context) WriteClipboard

func (_handle *Context) WriteClipboard(s string)

type Cursor

type Cursor uint8

Cursor is a pointer shape.

type Direction

type Direction uint8

Direction is the direction an interface reads in: left to right, or right to left, as Arabic and Hebrew are, as Flutter's TextDirection, SwiftUI's LayoutDirection and CSS's direction say.

A window takes the direction of the app's language (package golet sets it), and an element that of the element it is built in, unless it is given one (Element.Direction). Right to left, a Row lays its children out from the right, the Start of Justify, AlignItems and TextAlign is the right, a grid's columns go from the right, the logical edges (PaddingStart, MarginStart, Start, AnchorTopStart, ...) are on the right, horizontal scrolling starts at the right with its offsets counted from there, the vertical scroll bar is on the left, and the controls mirror what points along the line: arrows, chevrons, the fill of sliders and progress bars, switches, and where popups open. Paragraphs without a strongly directional character, as numbers, read right to left; the others take the direction of their first strong character either way.

As in Godot, the coordinate system is not mirrored: X still grows to the right, in Rect, in Draw's painter and in pointer positions, and what is physical stays so, as in CSS: Left, Right, Padding's left and right, AnchorTopLeft. Text, images and icons are not mirrored; draw what must point the other way after reading Context.Direction.

const (
	LeftToRight Direction = iota
	RightToLeft
)

func (Direction) String

func (d Direction) String() string

type DraggableOptions

type DraggableOptions struct {
	// Axis is the direction the element moves in: Horizontal, Vertical,
	// or, when zero, both.
	Axis Orientation
	// Bounds, if set, holds the element's offset within it at rest: from
	// X to X+W across, and from Y to Y+H down. The pointer drags the
	// element past them less and less far, as iOS holds content pulled
	// past its edges (Rubberband), and it goes back within them once let
	// go; Rigid stops it at them.
	Bounds *Rect
	Rigid  bool
	// Snap, if set, chooses where the element comes to rest once let go,
	// from where the throw would carry it (Project, held within Bounds):
	// as the nearest of a sheet's heights or of a pager's pages (Nearest).
	// A Snap returning its point lets the element glide there. Without
	// Snap, the element rests where the pointer lets it go. What Snap
	// returns along an axis the element does not move along is ignored.
	Snap func(Point) Point
	// Animation is how the element goes to rest, and to an offset the app
	// sets: Smooth's spring when zero. A spring starts at the pointer's
	// velocity as it lets go.
	Animation Animation
}

DraggableOptions are how an element that the pointer drags moves (Element.Draggable), and where it comes to rest once let go.

type Easing

type Easing func(t float32) float32

Easing maps the time an animation has run, from 0 to 1 of its duration, to how far its value has gone, as CSS's timing functions do. Linear, EaseIn, EaseOut and EaseInOut are easings, and Bounce makes more.

func Bounce

func Bounce(ease Easing) Easing

Bounce returns an easing that goes along ease and comes back, in the same time, as a pulse does.

func CubicBezier

func CubicBezier(x1, y1, x2, y2 float32) Easing

CubicBezier returns the easing of the cubic Bézier curve from (0, 0) to (1, 1) through the control points (x1, y1) and (x2, y2), as CSS's cubic-bezier(): x1 and x2 within 0 and 1.

type Effect

type Effect interface {
	// EffectMargin returns how far beyond the element's box, in DIPs
	// across and down, the effect reads its content: the content renders
	// that much around the box, as shadows painted beyond it, and reads as
	// transparent further away.
	EffectMargin() Point
	// PaintEffect paints the element, its box in DIPs, from content, the
	// element and its children rendered with p's scale, the box and the
	// margin around it: inset is where the box's corner lies in content,
	// in its pixels.
	PaintEffect(p *Painter, box Rect, content *Bitmap, inset Point)
}

Effect draws an element from what it renders, as SwiftUI's colorEffect, distortionEffect and layerEffect do: package ui/shader's effects (shader.Effect), which change each pixel's color, move the pixels, or read the content anywhere. The element and its children render into a bitmap, which the effect then draws over the element's box, in its place. Hit testing, focus and accessibility do not change: only what shows.

type EffectBackdrop

type EffectBackdrop struct {
	ToFrame [2][3]float32
	Origin  [2]float32
	Down    float32
	W, H    int
}

EffectBackdrop is where the backdrop of an effect lies (Painter. EffectBackdrop), as the renderers capture it: ToFrame maps a point in DIPs from a corner to the frame's pixels (x' = ToFrame[0]·(x, y, 1), y' = ToFrame[1]·(x, y, 1)); the texels start at Origin, in the frame's pixels, each Down pixels across, W×H of them.

type Element

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

Element is a 16-byte, checked handle to a private pooled node. The zero value is absent. It expires before the next build pass, even in the same frame. Keep a Handle for persistent identity.

func Accordion

func Accordion(c *Context, fn func()) Element

Accordion creates sections, one above the other in a bordered box, that fn builds with AccordionItem. Each opens and closes on its own; Up and Down move the focus between their headers, as do Home and End.

ui.Accordion(c, func() {
	ui.AccordionItem(c, "General", &app.general, func() { ... })
	ui.AccordionItem(c, "Privacy", &app.privacy, func() { ... })
})

For one section open at a time, close the others as one opens:

for i, s := range sections {
	open := app.section == i
	if ui.AccordionItem(c, s.Title, &open, s.Build).Changed() {
		app.section = -1
		if open {
			app.section = i
		}
	}
}

func AccordionItem

func AccordionItem(c *Context, title string, open *bool, fn func()) Element

AccordionItem creates a section of an Accordion: a header showing title, which a click opens and closes, as do Enter and Space, and below it what fn builds while *open is true. Changed reports a click.

func Autocomplete

func Autocomplete(c *Context, value *string, suggestions []string) Element

Autocomplete creates a text input editing *value, which suggests below it those of suggestions containing what was typed, those starting with it first: Up and Down move among them and Enter takes one, as does a click, while Enter on none is Submitted. Changed reports a change, typed or taken. Name it with Label.

ui.Autocomplete(c, &app.city, cities).Label("City")

func Avatar

func Avatar(c *Context, name string, image *Bitmap) Element

Avatar creates a picture of a person or a thing named name: the image, cropped to a circle, or the initials of name on a color it picks from it, as high as twice the font size. Assistive technology sees an image named name.

func BackButton

func BackButton(c *Context, r *Router) Element

BackButton creates a button going back in r's history, disabled at its start, as in the toolbar of Finder or a browser; a right click lists the pages before, to go back several. ForwardButton goes forward again.

func Badge

func Badge(c *Context, text string) Element

Badge creates a short text in a pill, as a count of unread messages beside a sidebar's item.

func Box

func Box(c *Context) Element

Box creates a container that lays its children out in a column.

func Breadcrumbs(c *Context, items []string, chosen *int) Element

Breadcrumbs creates a path of items, as Finder's path bar and AppKit's path control, separated by chevrons: the items but the last are links, which a click chooses, as Enter does, setting *chosen to its index, which Changed reports. Long items shorten with an ellipsis as room runs short. Assistive technology sees links in a group; name it with Label.

path := []string{"Macintosh HD", "Users", "ada", "Documents"}
if ui.Breadcrumbs(c, path, &app.chosen).Label("Path").Changed() {
	app.open(path[:app.chosen+1])
}

func Button

func Button(c *Context, label string) Element

Button creates a button showing label. Ask Clicked whether it was clicked; give it other content with Children and an empty label.

func ButtonBase

func ButtonBase(c *Context) Element

ButtonBase creates a button without a look: a row centering its children that takes the keyboard focus, and reports Clicked for the pointer, Enter and Space. Style it and give it children; Button is ButtonBase with the theme's look.

func Calendar

func Calendar(c *Context, date *time.Time) Element

Calendar creates a month's calendar choosing *date, as SwiftUI's graphical date picker, in the window's language, its weeks starting on the first day of the user's regional formats (Context.Region): a click chooses a day, as the arrows do while the calendar has the focus, Page Up and Page Down or its buttons move by months, and Home and End go to the first and the last day of the month. Changed reports a new date, which keeps the time of day and location of *date. Assistive technology reads the day chosen as the arrows move.

func Checkbox

func Checkbox(c *Context, checked *bool, label string) Element

Checkbox creates a check box toggling *checked, with a label.

func CheckboxBase

func CheckboxBase(c *Context, checked *bool) Element

CheckboxBase creates a check box without a look: a row that toggles *checked when clicked, or with Space while it has the focus, which Changed reports, and that assistive technology sees as a check box, checked or not. Draw its box from *checked; Checkbox is CheckboxBase with the theme's look.

func CheckboxGroup

func CheckboxGroup(c *Context, label string, fn func()) Element

CheckboxGroup creates a check box over the check boxes that fn builds, indented below it, as a list of permissions: it is checked when they all are, mixed when some are, and a click, or Space while it has the focus, checks them all, or none when they all are. Changed reports a click. Assistive technology sees a check box, mixed while some are checked, and a group of the others named by label.

ui.CheckboxGroup(c, "Notifications", func() {
	ui.Checkbox(c, &app.mail, "Mail")
	ui.Checkbox(c, &app.calendar, "Calendar")
})

func Collapsible

func Collapsible(c *Context, label string, open *bool, fn func()) Element

Collapsible creates a disclosure, as SwiftUI's DisclosureGroup: label beside an arrow, which a click opens and closes, as do Enter and Space, showing below it what fn builds while *open is true. The arrow turns and the content grows into view as it opens. Changed reports a click.

ui.Collapsible(c, "Advanced", &app.advanced, func() {
	ui.Checkbox(c, &app.verbose, "Verbose logging")
})

func ColorPicker

func ColorPicker(c *Context, color *Color) Element

ColorPicker creates a picker of *color, as AppKit's color panel: a square choosing the saturation, across, and the brightness, up, of the hue its slider chooses below it, a slider of opacity, the color in hex, which the user edits, and swatches of common colors. The arrows move across the square while it has the focus, Up and Down changing the brightness and Left and Right the saturation. Changed reports a new color.

func ColorWell

func ColorWell(c *Context, color *Color) Element

ColorWell creates a swatch of *color that opens a ColorPicker below it, as AppKit's color well: a click, Enter or Space opens it, and Escape or a click outside closes it. Changed reports a new color. Assistive technology sees a color well whose value is the color in hex; name it with Label.

func Column

func Column(c *Context) Element

Column creates a container that lays its children out from top to bottom, stretched to its width.

func Combobox

func Combobox(c *Context, selected *string, options []string) Element

Combobox creates a combobox choosing *selected among options: a field showing the choice, whose text filters the options below it as the user types, those starting with it first, while a click or Down shows them all; a click showing them selects the choice, for typing to replace. Up and Down move among them and Enter chooses, as does a click; Escape closes them, and the text goes back to the choice when the field loses the focus. Changed reports a new choice. Name it with Label.

ui.Combobox(c, &app.font, fonts).Label("Font")

func DateInput

func DateInput(c *Context, date *time.Time) Element

DateInput creates a field showing *date in the user's regional formats, as 1/5/2026 in the United States, which a calendar below it changes. A click, Enter or Space opens the calendar, where a click chooses a day, as do the arrows and Enter; Page Up and Page Down, or its buttons, move by months, and Escape closes it. Changed reports a new date, which keeps the time of day and location of *date.

func DialogBase

func DialogBase(c *Context, open *bool, fn func(backdrop Element, panel Element)) Element

DialogBase shows a dialog without a look over the window while *open is true: fn styles the backdrop covering the window, which centers the panel, and the panel, and builds the panel's content. Clicking the backdrop or pressing Escape sets *open to false, which Dismissed reports. It returns the panel, or nil while closed; Modal is DialogBase with the theme's look.

func Divider

func Divider(c *Context) Element

Divider creates a thin line across its row or column.

func EditableText

func EditableText(c *Context, value *string) Element

EditableText shows *value as a text that the user edits in place, as a file's name in Finder: a double click on it, or Enter while it has the focus, shows a text input of it, with the text before its extension selected. Enter keeps what was typed, as moving the focus away does, and Escape goes back; Changed reports a new value.

In a List's or a Table's rows, the list keeps the focus and the text takes none: Enter on macOS, and F2, edit the text of the row chosen, while a double click on the row is Submitted; a click on the text of a row already chosen edits it, once a second click would no longer make a double click.

ui.Table(c, &app.files, cols, len(app.names), func(row, col int) {
	if ui.EditableText(c, &app.names[row]).Changed() {
		app.rename(row)
	}
})

func Field

func Field(c *Context, label string, fn func()) Element

Field creates a field: label, above the control that fn builds, or beside it in a Form. The label names the control for assistive technology, unless the control names itself, as a check box with its own text does, when it names the field around it; a click on the label focuses the control, or clicks a check box, a switch or a radio button. Description and Error add texts below the control, which describe it:

ui.Field(c, "Email", func() {
	ui.TextInput(c, &app.email)
}).Description("For receipts.").Error(app.emailError)

The control is the first element fn builds that takes the focus, or a group of them, such as a RadioGroup.

func Fieldset

func Fieldset(c *Context, legend string, fn func()) Element

Fieldset creates a group of the fields that fn builds, under legend, which names the group for assistive technology. Disabled disables them all. In a Form, their labels line up with those of the other fields.

ui.Fieldset(c, "Shipping", func() {
	ui.Field(c, "Address", func() { ui.TextInput(c, &app.address) })
})

func FindBar

func FindBar(c *Context, open *bool, query *string, matches int, current *int) Element

FindBar creates a bar for finding text while *open is true, as Safari's and Xcode's: a field of *query, which takes the focus as the bar opens, how many matches there are of matches, previous and next buttons choosing *current among them, and Done. Enter in the field goes to the next match, Shift+Enter to the previous, as do Cmd+G and Shift+Cmd+G on macOS, F3 and Shift+F3 elsewhere, round the ends; Escape and Done close the bar. The app finds: it counts the matches of *query and shows match *current, which Changed reports moving. Assistive technology hears the count as it changes. While closed, it returns an element showing nothing.

func Form

func Form(c *Context, fn func()) Element

Form creates a column of the fields that fn builds (Field, Fieldset), whose labels sit in a column of their own, beside the controls, as in macOS's forms: aligned to the right, as wide as the widest, and level with the first line of their control.

ui.Form(c, func() {
	ui.Field(c, "Name", func() { ui.TextInput(c, &app.name) })
	ui.Field(c, "Size", func() { ui.Select(c, &app.size, sizes) })
})

func ForwardButton

func ForwardButton(c *Context, r *Router) Element

ForwardButton creates a button going forward in r's history, as BackButton goes back.

func Grid

func Grid(c *Context) Element

Grid creates a grid: its children fill its cells row by row, or go where ColumnStart and RowStart put them, spanning ColumnSpan columns and RowSpan rows. Columns and ColumnTracks set its columns; it adds rows as its children need them.

ui.Grid(c).Columns(3).Gap(12).Children(func() {
	for _, p := range photos {
		ui.Image(c, p).AspectRatio(1).Fit(ui.Cover)
	}
})

func GridView

func GridView(c *Context, s *GridState, n int, minWidth float32, height float32, item func(i int)) Element

GridView creates a scroll container of n items in a grid, as Photos' library and Finder's icon view, built with item(i): as many columns as fit items at least minWidth wide, which share the width left, and rows height high, built only as they show, so grids of millions of items are as fast as small ones. Gap spaces the items.

s keeps the place and says how items are chosen, or nil: with s.Selected, a click chooses an item, as the arrow keys do in two dimensions while the grid has the keyboard focus, with Home, End and the first letters of an item's Label.

app.photos.Selected = &app.photo
ui.GridView(c, &app.photos, len(photos), 140, 120, func(i int) {
	ui.Image(c, thumbs[i]).Fit(ui.Contain).Grow(1)
}).Grow(1)

func Icon

func Icon(c *Context, s *SVG) Element

Icon creates an element showing an SVG as an icon: its shapes in the color of the text, which it takes from its ancestors as text does (TextColor), whatever colors the SVG has. It is as high as the font size (FontSize), keeping the SVG's aspect ratio, unless given a size, and does not stretch across a column. Icons are decorations that assistive technology does not see, unless Label names them.

ui.Row(c).Gap(6).Children(func() {
	ui.Icon(c, save)
	ui.Text(c, "Save")
})

func Image

func Image(c *Context, src ImageSource) Element

Image creates an element showing a bitmap, or an SVG in its own colors (with the text color for its currentColor), by default at its size as DIPs, scaled to fit when given another size.

func Link(c *Context, label string, url string) Element

Link creates a text that opens url in the browser when clicked, or Enter while it has the focus. In a page of a Router, a path without a scheme, as "/notes/42" or "edit", goes there in the router (Push). Inside a RichText it is a link within the paragraph; give it an empty label and Children to style parts of its text.

func List

func List(c *Context, s *ListState, n int, row ...func(int)) Element

List creates a virtual list. The original row callback remains supported. Omit it to configure ItemKey and Selection, then call Rows.

func MenuButton(c *Context, label string, build func(m *Menu)) Element

MenuButton creates a button showing label and an arrow, which opens a menu below it that build fills with items, as the pointer goes down on it or for Enter, Space or Down while it has the focus (Element.Menu):

ui.MenuButton(c, "Sort by", func(m *ui.Menu) {
	for _, by := range []string{"Name", "Date", "Size"} {
		if m.Item(by).Checked(app.sort == by).Chosen() {
			app.sort = by
		}
	}
})

func Meter

func Meter(c *Context, value float64, lo float64, hi float64, levels *MeterLevels) Element

Meter creates a bar showing value between lo and hi, as AppKit's level indicator and the web's meter: the theme's Success color, or Warning and Danger from the levels given, nil for none. Assistive technology sees a level indicator of that value; name it with Label.

ui.Meter(c, app.disk.Used, 0, app.disk.Size, &ui.MeterLevels{Warning: 0.8 * size, Critical: 0.95 * size}).Label("Disk")
func Modal(c *Context, open *bool, fn func()) Element

Modal shows a dialog built by fn over a dimmed window while *open is true; clicking outside it or pressing Escape sets *open to false, which Dismissed reports.

func NumberInput

func NumberInput(c *Context, value *float64, lo float64, hi float64, step float64) Element

NumberInput creates a text input editing *value as a number between lo and hi, which the arrows Up and Down, and the buttons beside it, step by step. What is typed applies as soon as it is a number in range, and shows rounded to the decimals of step once the input loses the focus. Changed reports a new value.

ui.NumberInput(c, &app.copies, 1, 99, 1)

func Outline

func Outline[K comparable](c *Context, s *OutlineState[K], roots []K, children func(arg0 K) []K, row func(item K)) Element

Outline creates a list of items in a tree, as AppKit's outline view and SwiftUI's List of children: roots at the top, and below each item open its children, indented, which children returns, nil for an item without any. A click on an item's arrow opens or closes it, with all its children's children with Option (Alt). row builds the content of an item's row, after its arrow; Gap, Padding and the rest are a List's.

The outline builds only the rows in view, as a List does, so trees of any size are as fast as small ones. With s.List.Selected or Selection, rows are chosen as a List's, and while the outline has the focus, Right opens the item chosen or goes to its first child, and Left closes it or goes to its parent, with Option on macOS and Shift elsewhere, as in GTK, opening and closing all inside.

app.files.List.Selected = &app.file
ui.Outline(c, &app.files, []string{"/"}, func(dir string) []string {
	return app.children[dir] // nil for files
}, func(path string) {
	ui.Text(c, filepath.Base(path))
}).Grow(1)

func OutlineTable

func OutlineTable[K comparable](c *Context, s *OutlineState[K], columns []TableColumn, roots []K, children func(arg0 K) []K, cell func(item K, col int)) Element

OutlineTable creates an outline whose rows are a Table's, as AppKit's outline view with columns: the first of columns shows the items' arrows, indented as they are deep, before what cell builds. It takes the columns, the sort and the keys of a Table, and those of an Outline.

ui.OutlineTable(c, &app.files, cols, roots, children, func(path string, col int) {
	switch col {
	case 0:
		ui.Text(c, filepath.Base(path)).SingleLine()
	case 1:
		ui.Text(c, app.size(path))
	}
})

func Popover

func Popover(c *Context, anchor Element, open *bool, fn func()) Element

Popover shows fn's elements in a panel below anchor while *open is true; clicking outside it or pressing Escape sets *open to false, which Dismissed reports.

func PopoverBase

func PopoverBase(c *Context, anchor Element, open *bool, fn func(panel Element)) Element

PopoverBase shows a panel without a look below anchor while *open is true: fn styles the panel and builds its content. Pressing outside the panel and the anchor, or Escape, sets *open to false, which Dismissed reports; the press goes on to what is under the pointer, as with the web's popovers. It starts at the anchor's start: its left, or its right right to left (Direction). Where there is no room below the anchor, the panel shows above it; a top margin keeps it apart from the anchor on either side. fn may place it elsewhere with AttachTo, as after the anchor:

panel.AttachTo(anchor, ui.AnchorEnd, ui.AnchorStart).MarginStart(6)

It returns the panel, or nil while closed; Popover is PopoverBase with the theme's look.

func PrimaryButton

func PrimaryButton(c *Context, label string) Element

PrimaryButton creates a button in the accent color, for the main action.

func Progress

func Progress(c *Context, value float64) Element

Progress creates a progress bar filled to value between 0 and 1; a negative value shows activity of unknown length. It fills from its start: the right right to left (Direction). Reverse fills it from the other side.

func Radio

func Radio[T comparable](c *Context, selected *T, value T, label string) Element

Radio creates a radio button that selects value into *selected, with a label.

func RadioBase

func RadioBase[T comparable](c *Context, selected *T, value T) Element

RadioBase creates a radio button without a look: a row that selects value into *selected when clicked, or with Space while it has the focus, which Changed reports, and that assistive technology sees as a radio button, on when *selected is value. Radio is RadioBase with the theme's look.

func RadioGroup

func RadioGroup(c *Context, fn func()) Element

RadioGroup creates a column of the radio buttons that fn builds (Radio, RadioBase), which are one stop of Tab: Tab goes to the one chosen, and the arrows choose among them, as do Home and End. Assistive technology sees a radio group; name it with Label. Make it a row with Row.

ui.RadioGroup(c, func() {
	for _, size := range []string{"Small", "Medium", "Large"} {
		ui.Radio(c, &app.size, size, size)
	}
}).Label("Size")

func RangeSlider

func RangeSlider(c *Context, low *float64, high *float64, lo float64, hi float64, step float64) Element

RangeSlider creates a slider of two knobs setting *low and *high between lo and hi, as a price range: each knob takes the focus, which Tab moves between, and the arrows, Home and End move it while it has the focus; a press on the track moves the knob nearest to it. A step above 0 snaps the values to lo and multiples of step from it, with tick marks. Changed reports a new value. Assistive technology sees two sliders, named by the RangeSlider's Label and "minimum" and "maximum".

func Rating

func Rating(c *Context, value *int, max int) Element

Rating creates a row of max stars, as AppKit's rating level indicator, of which *value are filled: a click on a star sets it, a click on the star set clears it, and the arrows, Home and End change it while the rating has the focus. Changed reports a new value. Assistive technology sees a slider from 0 to max; name it with Label.

func RichText

func RichText(c *Context, spans ...Span) Element

RichText creates a text whose spans differ in style, over the style of the text, which its methods and the elements around it set as for Text:

ui.RichText(c,
	ui.Span{Text: "Saved "},
	ui.Span{Text: "report.pdf", Weight: 600},
	ui.Span{Text: " to "},
	ui.Span{Text: "Documents", Color: t.Accent, Underline: true},
)

The spans wrap together as one paragraph, or several at newlines.

Text elements built in its Children (Text, Link, RichText) continue the paragraph after its spans, as HTML's inline elements do: each styles its own text over the paragraph's, and keeps its interaction (Clicked, Hovered, the focus, a Tooltip, assistive technology) with its words as its area. A link in a sentence:

ui.RichText(c).Children(func() {
	ui.Text(c, "Read ")
	ui.Link(c, "the guide", url)
	ui.Text(c, " to get started.")
})

Only text elements go inside a text, and their sizes, padding, borders and corners do not apply; a background highlights their text.

func Row

func Row(c *Context) Element

Row creates a container that lays its children out from left to right, centered vertically.

func Scroll

func Scroll(c *Context) Element

Scroll creates a container that scrolls its children vertically. Give it a size, or Grow it within its parent.

func ScrollBoth

func ScrollBoth(c *Context) Element

ScrollBoth creates a container that scrolls its children both ways, as a canvas, a wide table or code does. Give it a size, or Grow it within its parent.

func ScrollHorizontal

func ScrollHorizontal(c *Context) Element

ScrollHorizontal creates a row that scrolls its children horizontally.

func SearchField

func SearchField(c *Context, query *string) Element

SearchField creates a field for searching, editing *query: a magnifying glass, the text, and a button clearing it while it holds any, as Escape does then. Enter is its Submitted, and Changed reports a change. It shows Search while empty, and assistive technology sees a search field; name it with Label.

if ui.SearchField(c, &app.query).Label("Search mail").Changed() {
	app.filter()
}

func Segmented

func Segmented(c *Context, selected *int, labels ...string) Element

Segmented creates a segmented control showing labels, of which *selected is the index of the one chosen, as a switch between views: a click chooses a segment, as do the arrows while it has the focus, and Changed reports a new choice. Assistive technology sees a radio group; name it with Label. For icons, build the segments with SegmentedBase.

ui.Segmented(c, &app.view, "List", "Grid").Label("View")

func Select

func Select(c *Context, selected *string, options []string) Element

Select creates a drop-down choosing one of options into *selected.

func Sidebar(c *Context, selected *string, fn func()) Element

Sidebar creates a sidebar of the sections and the items that fn builds (SidebarSection, SidebarItem), as Finder's and Mail's, scrolling when they do not fit: a click chooses an item, whose ID *selected holds, and while the sidebar has the focus, Up and Down choose among its items, as do Home, End and typing the first letters of an item. It is one stop of Tab, and Changed reports a new choice. Give it a width:

ui.Sidebar(c, &app.mailbox, func() {
	ui.SidebarSection(c, "Mailboxes", &app.mailboxes, func() {
		ui.SidebarItem(c, "inbox", inboxIcon, "Inbox").Children(func() {
			ui.Badge(c, "12")
		})
		ui.SidebarItem(c, "sent", sentIcon, "Sent")
	})
}).Width(220)

Assistive technology sees a tree, whose sections hold their items.

func SidebarItem

func SidebarItem(c *Context, id string, icon *SVG, label string) Element

SidebarItem creates an item of a Sidebar choosing id, showing label after icon, nil for none. Add to it with Children, as a Badge.

func SidebarSection

func SidebarSection(c *Context, title string, open *bool, fn func()) Element

SidebarSection creates a section of a Sidebar under title, holding the items fn builds while *open is true, as Finder's: a click on the title shows and hides them, as does its arrow, which shows as the pointer rests on the title. A nil open keeps the section open.

func Slider

func Slider(c *Context, value *float64, lo float64, hi float64) Element

Slider creates a slider setting *value between lo and hi.

func SliderBase

func SliderBase(c *Context, value *float64, lo float64, hi float64) Element

SliderBase creates a slider without a look: dragging across its content box, within its padding, sets *value between lo and hi, as do the arrows, Home and End while it has the focus, by a hundredth of the range unless Step says otherwise; Changed reports a new value, and assistive technology sees a slider of that range. Draw its track and thumb where (*value-lo)/(hi-lo) puts them, and pad it by half the thumb's width to keep the thumb inside it. Right to left (Context.Direction), lo is at the right of the content box, as the arrows go: draw it mirrored.

s := ui.SliderBase(c, &app.volume, 0, 100).Height(24).PaddingX(12)
s.Draw(func(p *ui.Painter, r ui.Rect) {
	x := r.X + 12 + (r.W-24)*float32(app.volume/100)
	p.Fill(ui.Rect{X: r.X + 12, Y: r.Y + 10, W: r.W - 24, H: 4}, gray, 2)
	p.Fill(ui.Rect{X: x - 12, Y: r.Y, W: 24, H: 24}, blue, 12)
})

Vertical makes it go up from lo at the bottom. Slider is SliderBase with the theme's look.

func Spacer

func Spacer(c *Context) Element

Spacer creates an empty element that takes the free space of its row or column, pushing its siblings apart.

func Spinner

func Spinner(c *Context) Element

Spinner creates an indicator of work of unknown length, as AppKit's spinning progress indicator: spokes turning, as high as the font size, in the theme's muted text color, or the color TextColor gives it, as one on a chosen row of a list needs. Assistive technology sees a progress indicator of unknown length; name it with Label.

func Split

func Split(c *Context, size *float32, first func(), second func()) Element

Split lays out first and second side by side, with a divider between them that the user drags to resize them, or moves with the arrows once it has the keyboard focus: *size is the width of first, which the divider keeps 40 DIPs from either edge. With less room than that, first gives way, keeping *size for when there is room again. Changed reports a move. Right to left (Direction), first is on the right.

ui.Split(c, &app.sidebar, app.files, app.editor).Fill()

func SplitPercent

func SplitPercent(c *Context, p *float32, first func(), second func()) Element

SplitPercent is Split with *p the percentage of the room first takes, from 0 to 100, so that both panes grow and shrink with the room, in proportion.

ui.SplitPercent(c, &app.sidebarPercent, app.files, app.editor).Fill()

func SplitVertical

func SplitVertical(c *Context, size *float32, first func(), second func()) Element

SplitVertical is Split with first above second, *size its height.

func SplitVerticalPercent

func SplitVerticalPercent(c *Context, p *float32, first func(), second func()) Element

SplitVerticalPercent is SplitPercent with first above second.

func StepSlider

func StepSlider(c *Context, value *float64, lo float64, hi float64, step float64) Element

StepSlider creates a slider setting *value to lo or a multiple of step from it, up to hi, with a tick mark at each, as AppKit's sliders with tick marks: dragging snaps to them, and the arrows step by step.

func Stepper

func Stepper(c *Context, value *float64, lo float64, hi float64, step float64) Element

Stepper creates a pair of arrows changing *value by step between lo and hi, as AppKit's stepper beside a field: a click on an arrow steps up or down, as do Up and Down while the stepper has the focus, and holding an arrow keeps stepping. Changed reports a new value. Assistive technology sees a spin button; name it with Label.

func Switch

func Switch(c *Context, on *bool) Element

Switch creates a switch toggling *on.

func SwitchBase

func SwitchBase(c *Context, on *bool) Element

SwitchBase creates a switch without a look: CheckboxBase, which assistive technology sees as a switch. Switch is SwitchBase with the theme's look.

func Table

func Table(c *Context, s *ListState, columns []TableColumn, n int, cell func(row int, col int)) Element

Table creates a table of n rows under a header of columns, whose rows are a List's: it builds only those in view, cell building the content of a row's column, usually a Text. Rows are as high as their tallest cell, and at least as high as the header.

s keeps the place of the rows and says how they behave, as a List's, or nil: with s.Selected, a click chooses a row, as Up, Down, Home and End do while the table has the keyboard focus, Changed reports a new choice, and Submitted a double click or Enter on it; with s.Selection, the user chooses several. A row s.Header names spans every column, cell building it as column 0, and stays at the top while the rows of its section scroll under it.

The user resizes columns by dragging the edges of their headers, and moves them by dragging the headers, which s.Columns keeps; columns wider than the table scroll sideways, the header with them. With s.Sort, a click on the header of a Sortable column sorts the rows by it; with s.SortBy, a Cmd-click or a Shift-click sorts by it after the others; with s.HeaderMenu, the header has a context menu.

cols := []ui.TableColumn{{Title: "Name", Sortable: true}, {Title: "Size", Width: 90, Align: ui.End, Sortable: true}}
app.files.Selected, app.files.Sort = &app.file, &app.sort
if ui.Table(c, &app.files, cols, len(files), func(row, col int) {
	f := files[row]
	switch col {
	case 0:
		ui.Text(c, f.Name).SingleLine()
	case 1:
		ui.Text(c, f.Size())
	}
}).Grow(1).Submitted() {
	app.open(files[app.file])
}

func Tabs

func Tabs(c *Context, selected *int, labels ...string) Element

Tabs creates a row of tabs showing labels, of which *selected is the index of the one chosen. A click chooses a tab, as do the arrows, Home and End while one has the keyboard focus, which follows the choice:

ui.Tabs(c, &app.tab, "General", "Appearance", "Advanced")
switch app.tab {
case 0:
	app.general(c)
…
}

Changed reports a new choice.

func Text

func Text(c *Context, s string) Element

Text creates a text, which wraps at the width it gets.

func TextArea

func TextArea(c *Context, value *string) Element

TextArea creates a multi-line text input editing *value.

func TextAreaBase

func TextAreaBase(c *Context, value *string) Element

TextAreaBase creates a multi-line text input without a look, editing *value: TextArea without its padding, background, border and corners.

func TextAreaBuffer

func TextAreaBuffer(c *Context, value *TextBuffer) Element

TextAreaBuffer creates a multiline control editing indexed storage. Ordinary edits and native queries never materialize the whole document. Layout retains the paragraphs in view, as TextArea does.

func TextAreaBufferBase

func TextAreaBufferBase(c *Context, value *TextBuffer) Element

func TextInput

func TextInput(c *Context, value *string) Element

TextInput creates a single-line text input editing *value.

func TextInputBase

func TextInputBase(c *Context, value *string) Element

TextInputBase creates a single-line text input without a look, editing *value: TextInput without its padding, background, border and corners.

func TextInputBuffer

func TextInputBuffer(c *Context, value *TextBuffer) Element

TextInputBuffer creates a single-line control editing indexed storage. It shares TextInput's selection, composition, undo and styling behavior.

func TextInputBufferBase

func TextInputBufferBase(c *Context, value *TextBuffer) Element

TextInputBufferBase and TextAreaBufferBase are the unstyled buffer controls.

func Textf

func Textf(c *Context, format string, args ...any) Element

Textf creates a text formatted with fmt.Sprintf.

func TimeInput

func TimeInput(c *Context, tm *time.Time) Element

TimeInput creates a field of the time of day of *tm, in the hour cycle of the user's regional formats (Context.Region): 15:04, or 3:04 PM with the window's language's names of the halves of the day, before the hours where the language writes them so (下午3:04). Its hours, minutes and half of the day each take the focus, as the segments of AppKit's date picker: Up and Down step the one with the focus round the clock, digits typed set it, going on to the minutes once the hours are typed, the first letter of a half of the day chooses it, and Left and Right move between them. Changed reports a new time, which keeps the date and the location of *tm. Assistive technology sees spin buttons, named after the field's Label and "hours", "minutes" and "AM/PM". It reads left to right in an interface laid out right to left too, as times are written there.

ui.TimeInput(c, &app.alarm).Label("Alarm")

func ToastViewportBase

func ToastViewportBase(c *Context, fn func(viewport Element, toasts []Toast)) Element

ToastViewportBase builds the window's toasts without a look, in place of the theme's: fn styles viewport, a column covering the window that the pointer goes through, which holds them at its bottom, and builds each of toasts with ToastBase, giving it the look of its Type and Data. toasts are those showing, the newest three, oldest first. Call it once in the view, wherever. Toasts in the bottom right corner:

ui.ToastViewportBase(c, func(viewport ui.Element, toasts []ui.Toast) {
	viewport.Padding(16).AlignItems(ui.End).Gap(8)
	for _, t := range toasts {
		toast := ui.ToastBase(c, t)
		toast.Root.Row().Gap(12).Padding(10, 14).Radius(8).Background(surface)
		toast.Root.Children(func() {
			ui.Text(c, t.Title).Grow(1)
			toast.CloseButton().Label("Close").Children(func() { ui.Icon(c, x) })
		})
	}
})

The time of the toasts stops while the pointer rests on viewport, the keyboard focus is in it, or the window is in the background. viewport stays while no toast shows, for the last one to go with an exit transition. It returns viewport.

func Toggle

func Toggle(c *Context, on *bool, label string) Element

Toggle creates a button that stays pressed while *on, as Bold in an editor's toolbar: a click presses it or lets it go, as does Space while it has the focus, and Changed reports a change. Give it other content, such as an icon, with Children and an empty label, and name it with Label:

ui.Toggle(c, &app.bold, "").Label("Bold").Children(func() { ui.Icon(c, boldIcon) })

func ToggleBase

func ToggleBase(c *Context, on *bool) Element

ToggleBase creates a toggle button without a look: a row that turns *on over when clicked, or with Space while it has the focus, which Changed reports, and that assistive technology sees as a toggle button, pressed while *on. Toggle is ToggleBase with the theme's look.

func ToggleGroup

func ToggleGroup(c *Context, fn func()) Element

ToggleGroup creates a row of the toggles and buttons that fn builds, drawn joined as the segments of one control, as Bold, Italic and Underline. They are one stop of Tab, among which the arrows move the focus, as in a toolbar; name the group with Label.

ui.ToggleGroup(c, func() {
	ui.Toggle(c, &app.bold, "B")
	ui.Toggle(c, &app.italic, "I")
}).Label("Style")

func TokenField

func TokenField(c *Context, tokens *[]string, suggestions []string) Element

TokenField creates a field of tokens, as of tags or the recipients of a mail: *tokens shows as chips, each with a button taking it out, before an input where Enter or a comma adds what was typed, and Backspace in it while empty takes out the last. The suggestions containing what was typed show below it, those not already tokens: Up and Down move among them, and Enter or a click adds one. Changed reports a change; name it with Label.

ui.TokenField(c, &app.tags, allTags).Label("Tags")

func Toolbar

func Toolbar(c *Context, fn func()) Element

Toolbar creates a row of the controls that fn builds, as along the top of a window: buttons, toggles, toggle groups, segmented controls and menu buttons, which take no face of their own until hovered. It is one stop of Tab, and Left and Right move the focus among its controls, Home and End to the first and the last; assistive technology sees a toolbar, which Label names. Controls that do not fit go, from the last, into a menu at its end, where choosing one clicks it. Spacer pushes those after it to the end.

ui.Toolbar(c, func() {
	ui.ToggleGroup(c, func() {
		ui.Toggle(c, &app.bold, "Bold")
		ui.Toggle(c, &app.italic, "Italic")
	})
	ui.Spacer(c)
	if ui.Button(c, "Share").Clicked() {
		app.share()
	}
}).Label("Format")

func TooltipBase

func TooltipBase(c *Context, anchor Element, fn func(tip Element)) Element

TooltipBase shows a tip without a look by anchor: fn styles the tip and builds its content. It shows once the pointer has rested on anchor for 0.6 seconds, at once as anchor gets the keyboard focus from the keyboard, and at once too within 0.4 seconds of another tip going, as the pointer moves along a toolbar. It goes as the pointer leaves anchor or presses it, and with Escape, until the pointer comes back or the focus does. Over elements inside one another, the innermost one's tip shows; one shows at a time.

The tip goes above anchor, centered, or below it where there is no room above; fn may place it elsewhere with AttachTo, as after it:

ui.TooltipBase(c, b, func(tip ui.Element) {
	tip.AttachTo(b, ui.AnchorEnd, ui.AnchorStart).MarginStart(6)
	tip.Padding(4, 8).Radius(6).Background(dark).TextColor(light)
	tip.Children(func() { ui.Text(c, "Share") })
})

The pointer goes through the tip, and assistive technology sees it as a tooltip, which it does not read: give anchor a Description to tell what the tip does. It returns the tip, or nil while it does not show; Element.Tooltip is TooltipBase with the theme's look.

func Tree

func Tree(c *Context, fn func()) Element

Tree creates a tree, whose items TreeItem builds in fn. While an item has the keyboard focus, Up and Down move it to the items around, Right opens the item or moves to its first child, and Left closes it or moves to its parent.

ui.Tree(c, func() {
	ui.TreeItem(c, "src", &app.srcOpen, func() {
		ui.TreeItem(c, "main.go", nil, nil)
	})
	ui.TreeItem(c, "go.mod", nil, nil)
})

func TreeItem

func TreeItem(c *Context, label string, open *bool, children func()) Element

TreeItem creates an item of a Tree showing label, inside the item it is built in. children builds the items inside it, which show while *open is true; nil children, or a nil open, makes a leaf. A click on its arrow opens or closes it; Clicked reports a click elsewhere on it, or Enter, for choosing it, which Selected shows.

func WebView

func WebView(c *Context, v NativeWebView) Element

WebView shows a web view, made with golet.Window.NewWebView, in the element's content box. A web view has no size of its own: the element stretches across its container (AlignSelf(Stretch)), and takes the room along it with Grow or a size:

ui.Row(c).Fill().Children(func() {
	sidebar(c)
	ui.WebView(c, app.docs).Grow(1)
})

The web view shows while a frame builds its element and hides when one does not, keeping its page: a view switching tabs builds the web view of the tab shown. The element paints a hole through the window's content (the web view is under it, the system's own view), as rounded as its Radius and cut by the scroll containers and clips around it, so that what paints after it shows over the page: its children, popovers, menus, dialogs, tooltips and toasts. The page takes the pointer where it shows and nothing painted over it takes it, and the keyboard once clicked, focused (golet.WebView.Focus) or tabbed into: Tab stops at the element. Its background and border paint around the page, which its opacity fades, and assistive technology finds the page inside it.

func (Element) Absolute

func (_handle Element) Absolute() Element

Absolute takes the element out of its parent's layout and places it with Top, Right, Bottom and Left relative to the parent's padding box, above its siblings. As in CSS, that box is inside the parent's border but holds its padding: Top(0) puts the element just below the border, whatever the padding.

func (Element) Access

func (_handle Element) Access(fn func(n *platform.AccessNode)) Element

Access has fn describe the element further to assistive technology, as it builds the element's node, only while assistive technology reads the window: what costs too much to give every frame, as the text of a large document. The node is a type internal to this module, so only its packages describe elements so, as package ui/editor does.

func (Element) ActiveDescendant

func (_handle Element) ActiveDescendant(d Element) Element

ActiveDescendant tells assistive technology that d has the keyboard focus while the element does: the option the arrows are on in a list or a menu that keeps the focus itself, as a combobox's input does. Call it once d is built, inside the element or in its popup.

func (Element) AlignContent

func (_handle Element) AlignContent(a Align) Element

AlignContent places the lines of a wrapping container across its main axis, as CSS's align-content does: Start (the default), Center, End, Stretch, SpaceBetween, SpaceAround or SpaceEvenly. In a grid it places the rows, which stretch when it is not set.

func (Element) AlignItems

func (_handle Element) AlignItems(a Align) Element

AlignItems places the children across the main axis.

func (Element) AlignSelf

func (_handle Element) AlignSelf(a Align) Element

AlignSelf places the element across its parent's main axis, overriding the parent's AlignItems; in a grid, it places the element in its cell vertically.

func (Element) Animate

func (_handle Element) Animate(key any, target float32, d time.Duration) float32

Animate returns a value that moves to target over d, easing out, and keeps frames coming while it moves; key tells apart the animations of the element. The value starts at the first target. When the desktop asks for less motion (Preferences.ReduceMotion), it goes to target at once. AnimateTo takes springs and delays too.

func (Element) AnimateColor

func (_handle Element) AnimateColor(key any, target Color, a Animation) Color

AnimateColor returns a color that goes to target as a says, mixed with premultiplied alpha as transitions mix colors, so that a color fading from transparent keeps its hue; key tells apart the element's animated colors. It starts at the first target. As changing colors moves nothing, colors still change smoothly while the desktop asks for less motion; DisableAnimations shows them at once.

func (Element) AnimatePose

func (_handle Element) AnimatePose(p Pose, a Animation) Element

AnimatePose moves the element to p as a says, after its own transform (Transform), and fades it, and returns the element. The element keeps going in frames that only paint, without building the view, as Core Animation and the Web Animations API run transforms and opacity: the cheapest motion there is, which a view large or slow to build keeps smooth. The pointer, carets and overlays follow it as they follow transforms. It starts at the first pose. While the desktop asks for less motion, it moves at once, and only fades smoothly.

card.AnimatePose(ui.Pose{Y: lift, Scale: 1.02}, ui.Snappy)

func (Element) AnimateTo

func (_handle Element) AnimateTo(key any, target float32, a Animation) float32

AnimateTo returns a value that goes to target as a says, and keeps frames coming while it moves; key tells apart the animated values of the element, which Animate, AnimateWith and Spring share. The value starts at the first target (Jump sets it elsewhere first). A new target on the way, or a new kind of Animation, takes over from where the value is: a spring keeps its velocity, even that of a curve. When the desktop asks for less motion (Preferences.ReduceMotion), the value goes to its target at once.

func (Element) AnimateWith

func (_handle Element) AnimateWith(key any, target float32, d time.Duration, ease Easing) float32

AnimateWith returns a value that moves to target over d as Animate does, along ease.

func (Element) Arrived

func (_handle Element) Arrived(key any) bool

Arrived reports whether the value animated under key came to rest at its target in this frame, after moving there: true in that frame only, for the view to go on, as by removing what faded out.

func (Element) AspectRatio

func (_handle Element) AspectRatio(r float32) Element

AspectRatio makes the height the width divided by r.

func (Element) Attach

func (_handle Element) Attach(at Anchor, self Anchor) Element

Attach takes the element out of its parent's layout, as Absolute does, and puts its point self on the point at of the parent's padding box: Attach(ui.AnchorTopRight, ui.AnchorCenter) centers a badge on the top right corner of its parent, and Attach(ui.AnchorBottomRight, ui.AnchorBottomRight) puts a button in the bottom right corner. Top, Right, Bottom and Left then move it from there; the element keeps its own size.

func (Element) AttachTo

func (_handle Element) AttachTo(target Element, at Anchor, self Anchor) Element

AttachTo takes the element out of its parent's layout, as Attach does, and puts its point self on the point at of target's box, wherever target is in the window: built in an Overlay, a panel goes below a button with AttachTo(button, ui.AnchorBottomLeft, ui.AnchorTopLeft), and to its right with AttachTo(button, ui.AnchorRight, ui.AnchorLeft). Where it would overflow the window, it goes to the other side of target, or the other way along it, if that overflows less, then moves along target into the window. Its margins keep it apart from target: a top margin below it, and above it as it goes there. Top, Right, Bottom and Left then move it; the element keeps its own size.

The element is target's popover: its elements follow target as Tab moves, and a press on target is not outside it (PressedOutside). Build target before it, in the same frame.

func (Element) AutoFocus

func (_handle Element) AutoFocus() Element

AutoFocus gives the element the keyboard focus in the frame it appears, as the first field of a dialog.

func (Element) BackfaceHidden

func (_handle Element) BackfaceHidden() Element

BackfaceHidden hides the element, and takes it from the pointer, while its 3D transform turns its back to the viewer, as CSS's backface-visibility: hidden: the two faces of a card turning over, the back turned 180 degrees more than the front, show one at a time.

front.RotateY(turn).Perspective(800).BackfaceHidden()
back.RotateY(turn + 180).Perspective(800).BackfaceHidden()

func (Element) Background

func (_handle Element) Background(c Color) Element

Background fills the element, in place of a gradient.

func (Element) Basis

func (_handle Element) Basis(v float32) Element

Basis sets the size along the parent's main axis before growing or shrinking.

func (Element) BasisPercent

func (_handle Element) BasisPercent(p float32) Element

BasisPercent sets the basis as a percentage of the parent's size along its main axis.

func (Element) Bind

func (e Element) Bind(r *Handle) Element

Bind gives the handle this control's identity in the current window.

func (Element) Blur

func (_handle Element) Blur(sigma float32) Element

Blur blurs the element, with its children, by sigma DIPs, the standard deviation of a Gaussian, as CSS's filter: blur() does: what it draws spreads that far around, transparent beyond, on the GPU. It renders into a bitmap first, as Effect does, about 3 sigma larger each way, and an element with an Effect draws through it instead. Hit testing, focus and accessibility do not change: only what shows.

func (Element) Bold

func (_handle Element) Bold() Element

Bold sets a bold font weight.

func (Element) Border

func (_handle Element) Border(width float32, c Color) Element

Border draws a border of width DIPs inside the element's edges, on every side; BorderWidth sets different widths. As in CSS, the border takes room within the element's size: the padding and the children are inside it.

func (Element) BorderColor

func (_handle Element) BorderColor(c Color) Element

BorderColor sets the color of the border.

func (Element) BorderConicGradient

func (_handle Element) BorderConicGradient(g ConicGradient) Element

BorderConicGradient paints the element's border (Border, BorderWidth) with a conic gradient around the element, in place of its color: a ring of colors, as SwiftUI's strokeBorder with an AngularGradient draws.

ui.Box(c).Size(120, 80).Radius(16).Border(4, ui.Color{}).BorderConicGradient(ui.ConicGradient{Stops: rainbow})

func (Element) BorderEndWidth

func (_handle Element) BorderEndWidth(v float32) Element

func (Element) BorderLinearGradient

func (_handle Element) BorderLinearGradient(g LinearGradient) Element

BorderLinearGradient paints the element's border (Border, BorderWidth) with a linear gradient across the element, in place of its color.

func (Element) BorderStartWidth

func (_handle Element) BorderStartWidth(v float32) Element

BorderStartWidth and BorderEndWidth set the width of the border on the side lines start and on the other, as PaddingStart does: a line between a sidebar and the content is BorderEndWidth(1) on the sidebar.

func (Element) BorderStyle

func (_handle Element) BorderStyle(s BorderStyle) Element

BorderStyle sets whether the border is solid, as by default, or dashed.

func (Element) BorderWidth

func (_handle Element) BorderWidth(v ...float32) Element

BorderWidth sets the widths of the border on each side, CSS style: all sides, vertical and horizontal, or top, right, bottom and left. A line below a header:

ui.Row(c).BorderWidth(0, 0, 1, 0).BorderColor(t.Border)

func (Element) Bottom

func (_handle Element) Bottom(v float32) Element

func (Element) BottomPercent

func (_handle Element) BottomPercent(p float32) Element

func (Element) Bounds

func (_handle Element) Bounds() Rect

Bounds returns the previous frame's transformed bounding rectangle in window DIPs; it is empty for an element the previous frame lacked. LayoutBounds returns its box before visual transforms.

func (Element) Center

func (_handle Element) Center() Element

Center centers the children along and across the main axis.

func (Element) Changed

func (_handle Element) Changed() bool

Changed reports whether this widget's value changed in this build pass, by the input it took as its constructor returned.

func (Element) Checked

func (_handle Element) Checked(on bool) Element

Checked tells assistive technology whether the element, as a check box, switch, radio button, toggle button or menu item of your own, is on. Bases set it from their value.

func (Element) Children

func (e Element) Children(fn func()) Element

Children builds children with the same context, scoped to this element. An absent element skips fn. Expired elements are diagnosed in development.

func (Element) ClickModifiers

func (_handle Element) ClickModifiers() Modifiers

ClickModifiers returns the modifier keys held as the element was last clicked, none for a click by the keyboard: with Clicked, a click with Shift or Cmd does something else, as extending a choice.

func (Element) Clicked

func (_handle Element) Clicked() bool

Clicked reports whether the element was clicked, with the primary button or by Enter or Space while focused, since the last frame.

func (Element) Clicks

func (_handle Element) Clicks() int

Clicks returns how many times the element was clicked since the last frame.

func (Element) Clip

func (_handle Element) Clip() Element

Clip hides what the children draw outside the element.

func (Element) ClipX

func (_handle Element) ClipX() Element

ClipX hides what the children draw left and right of the element, and ClipY what they draw above and below it.

func (Element) ClipY

func (_handle Element) ClipY() Element

func (Element) Column

func (_handle Element) Column() Element

Column lays the children out from top to bottom.

func (Element) ColumnSpan

func (_handle Element) ColumnSpan(n int) Element

ColumnSpan makes the element span n columns of its grid, or, for a negative n, every column from its start to the grid's last, as a header across a grid does.

func (Element) ColumnStart

func (_handle Element) ColumnStart(n int) Element

ColumnStart puts the element in column n of its grid, counting from 1.

func (Element) ColumnTracks

func (_handle Element) ColumnTracks(tracks ...Track) Element

ColumnTracks sets the grid's columns, as a sidebar and the rest:

ui.Grid(c).ColumnTracks(ui.Fixed(220), ui.Fr(1))

func (Element) Columns

func (_handle Element) Columns(n int) Element

Columns gives the grid n columns of equal width, Fr(1) each.

func (Element) Composing

func (_handle Element) Composing() bool

Composing reports whether an input method composes text in a text input, as Pinyin before a candidate is chosen: its value holds the text once composed. Keys typed meanwhile are the input method's, as Enter choosing a candidate: they submit nothing and press no shortcut.

func (Element) ConicGradient

func (_handle Element) ConicGradient(g ConicGradient) Element

ConicGradient fills the element with a conic gradient, its colors turning around a point (CSS's conic-gradient()):

ui.Box(c).Size(80, 80).Radius(40).ConicGradient(ui.ConicGradient{
	Stops: []ui.GradientStop{{red, 0}, {yellow, 1.0 / 3}, {blue, 2.0 / 3}, {red, 1}},
})

func (Element) ContentTransition

func (_handle Element) ContentTransition(t ContentTransition) Element

ContentTransition animates the element's content as it changes, as t says: the text of a Text, the icon of an Icon, the picture of an Image. Changes animate from frame to frame while the element is painted, in frames that only paint. While the desktop asks for less motion, content fades without moving.

ui.Text(c, strconv.Itoa(app.count)).ContentTransition(ui.ContentTransition{Numeric: true, Down: app.decreased})

func (Element) ContextMenu

func (_handle Element) ContextMenu(build func(m *Menu)) Element

ContextMenu gives the element a context menu, which build fills with items. The system shows it where the element is clicked with the secondary button, or Control-clicked on macOS, and, while the element or one inside it has the focus, below it when the menu key or Shift+F10 is pressed. build runs when the menu opens, and again in the frame after an item was chosen, where the item's Chosen reports it:

row.ContextMenu(func(m *ui.Menu) {
	if m.Item("Rename").Chosen() {
		app.renaming = i
	}
	m.Separator()
	if m.Item("Delete").Disabled(app.locked).Chosen() {
		app.delete(i)
	}
})

The innermost element with a context menu gets the click. Text inputs and selectable text have one with their editing commands, which ContextMenu replaces: on a text input, on a selectable text, or on the Selectable container whose text was clicked. EditItems puts those commands in a menu of one's own:

message.Selectable().ContextMenu(func(m *ui.Menu) {
	if m.Item("Reply").Chosen() {
		app.reply(msg)
	}
	m.Separator()
	m.EditItems()
})

func (Element) CopyData

func (_handle Element) CopyData(fn func(parts []SelectedText) transfer.Data) Element

CopyData sets what Copy, its shortcut and the context menu's put on the clipboard for the selection of a Selectable container: fn gets its parts, as SelectedTexts returns them, and returns the data, as a document copies its paragraphs with blank lines between them as text (transfer.TextData), and as HTML too to keep their formatting.

func (Element) Cursor

func (_handle Element) Cursor(c Cursor) Element

Cursor sets the pointer's shape over the element.

func (Element) Debug

func (_handle Element) Debug() Element

Debug outlines the element and every element inside it, with their padding and margins, to see the layout.

func (Element) DecorationColor

func (_handle Element) DecorationColor(c Color) Element

DecorationColor sets the color of underlines and strikethroughs, which is the text's otherwise.

func (Element) DecorationThickness

func (_handle Element) DecorationThickness(v float32) Element

DecorationThickness sets the thickness of underlines and strikethroughs in DIPs, which follows the font size otherwise.

func (Element) Description

func (_handle Element) Description(s string) Element

Description tells assistive technology more about the element than its name, as help text it reads after it. On a Field, the text shows below the control, and describes it.

func (Element) Direction

func (_handle Element) Direction(d Direction) Element

Direction lays the element and what is inside it out in d, whatever the direction around it: Direction(ui.LeftToRight) keeps a code sample, a phone number or a media player's controls left to right in a right-to-left window, as Flutter's Directionality and SwiftUI's layoutDirection environment do. The elements built inside it inherit it, as do the popups attached to it.

Give it right after creating the element, before its children, logical edges and the parts that read it, as widgets do as they are built: elements already inside take it, and logical edges move to the other side, but what read the old direction keeps it.

func (Element) Disabled

func (_handle Element) Disabled(d bool) Element

Disabled disables the element and those inside it when d is true: they report no clicks, take no focus, and widgets look disabled.

func (Element) Dismissed

func (_handle Element) Dismissed() bool

Dismissed reports whether pressing Escape or clicking outside closed the dialog or popover (Modal, DialogBase, Popover, PopoverBase) returning the element, in the frame it did, setting its *open to false: one that must stay open sets it back to true.

if ui.Modal(c, &app.editing, edit).Dismissed() && app.unsaved {
	app.editing = true
}

func (Element) Dividers

func (_handle Element) Dividers(width float32, c Color) Element

Dividers draws a line width DIPs thick in color c between each two children of a row, a column or a List (between their rows), across the element, inside its border: in the middle of the room between them, which the lines do not take, so give the element a Gap at least as wide. A row that wraps draws them between the children of each line; grids draw none.

func (Element) DoubleClicked

func (_handle Element) DoubleClicked() bool

DoubleClicked reports a double click on the element.

func (Element) Drag

func (_handle Element) Drag(value any) Element

Drag makes the element the source of value, dragged within the window once the pointer pressing the element moves a few DIPs: a copy of the element follows the pointer, and the element taking the value under it gets it when the pointer is released (Drop). A press dragging is no click. Dragging reports the drag.

func (Element) DragData

func (_handle Element) DragData(data transfer.Data, options ...transfer.DragOptions) Element

DragData makes e a native drag source after a primary press moves a few DIPs. Data can go to other windows and applications. A source also given Drag(value) offers that value to typed targets in this process only. The default operation is copy and the default preview is the element.

func (Element) DragDataFrom

func (_handle Element) DragDataFrom(data func() transfer.Data, options ...transfer.DragOptions) Element

DragDataFrom obtains a transfer when the gesture starts, useful for a changing selection. The function and options.Done run on the main thread. See transfer.Lazy for deferring individual serialized representations.

func (Element) DragEnded

func (_handle Element) DragEnded() (float32, float32, bool)

DragEnded reports whether the pointer pressing the element, and moving, let go since the last frame, with how fast it moved then, as DragVelocity: a spring taking over (SpringOptions.Velocity) keeps the fling going. A click, which does not move, ends no drag.

func (Element) DragOffset

func (_handle Element) DragOffset() Point

DragOffset returns where Draggable shows the element in this frame, from its place in the layout: following the pointer, or on its way to rest. Reading it builds the view in every frame the element moves in, as AnimateTo does, which the element otherwise moves in without: for what follows the element, as a backdrop fading as a sheet goes down. Call it after Draggable.

func (Element) DragVelocity

func (_handle Element) DragVelocity() (float32, float32)

DragVelocity returns how fast, in DIPs per second along the element's local axes, the pointer pressing the element moves now: zero once it stops for a moment, or while nothing presses the element.

func (Element) DragWindow

func (_handle Element) DragWindow() Element

DragWindow makes the element a handle that moves the window, such as the title bar of a frameless window. A double click on it maximizes the window, as on a title bar.

func (Element) Draggable

func (_handle Element) Draggable(offset *Point, o DraggableOptions) Element

Draggable lets the pointer move the element from its place in the layout, by *offset, and returns the element. As the pointer drags it, the element follows the pointer, along its parent's axes, and *offset with it; once the pointer lets go, *offset is where the element comes to rest, as o says, and it goes there. Setting *offset moves the element there as well, as o.Animation says. A nil offset is kept in the element.

The element moves after its own transform (Transform) and its pose (AnimatePose), and goes to rest in frames that only paint, without building the view, as AnimatePose moves it. Dragging reports that the pointer drags it, once the pointer moved a few DIPs, Transitioning that it moves, and DragOffset where it shows. A press dragging it is no click; a press catches it as it moves. While the desktop asks for less motion (Preferences.ReduceMotion), it goes to rest at once.

sheet.Draggable(&app.sheet, ui.DraggableOptions{
	Axis:   ui.Vertical,
	Bounds: &ui.Rect{H: 400},
	Snap:   ui.Nearest(ui.Point{}, ui.Point{Y: 200}, ui.Point{Y: 400}),
})

func (Element) Dragged

func (_handle Element) Dragged() (float32, float32, bool)

Dragged reports how far the pointer moved in the element's local axes since the last frame while pressing it.

func (Element) Dragging

func (_handle Element) Dragging() bool

Dragging reports whether the element is dragging its value (Drag), or the pointer is dragging the element (Draggable).

func (Element) Draw

func (_handle Element) Draw(fn func(p *Painter, r Rect)) Element

Draw paints on the element with p after its background, before its children; r is its box. fn only paints: it may run more than once a frame.

func (Element) DrawOver

func (_handle Element) DrawOver(fn func(p *Painter, r Rect)) Element

DrawOver paints on the element with p after its children.

func (Element) DroppedFiles

func (_handle Element) DroppedFiles() []string

DroppedFiles returns the paths of the files dropped on the element since the last frame, nil when none, and makes the element take files dragged over it.

func (Element) Effect

func (_handle Element) Effect(fx Effect) Element

Effect draws the element, with its children, through fx, an effect of package ui/shader, in place of drawing it as it is; nil draws it as it is:

ui.Text(c, "Wavy").Effect(wave.Effect(shader.Options{
	Uniforms:        map[string]any{"Time": t},
	MaxSampleOffset: ui.Point{Y: 8},
}))

What the element renders, with its children, shadows and what its Draw callbacks paint, renders into a bitmap of the GPU, the size of its box and the effect's margin (Effect.EffectMargin) around it, every frame the element paints, which the effect then draws over the box and the margin, transformed, clipped and faded as the element would be. Web views inside the element do not show through an effect.

func (Element) Ellipsis

func (_handle Element) Ellipsis(s string) Element

Ellipsis sets what ends text that MaxLines or SingleLine cuts, "…" by default.

func (Element) End

func (_handle Element) End(v float32) Element

func (Element) EndPercent

func (_handle Element) EndPercent(p float32) Element

func (Element) Error

func (_handle Element) Error(msg string) Element

Error marks the element's value as not valid, for msg, which assistive technology reads with it; an empty msg leaves it valid. On a Field, the message shows below the control in the theme's Danger color, and marks the control, whose border text inputs draw in that color.

func (Element) Expanded

func (_handle Element) Expanded(open bool) Element

Expanded tells assistive technology whether what the element opens shows, as the popup of a button or the section below a header.

func (Element) FileDragOver

func (_handle Element) FileDragOver() bool

FileDragOver reports whether files dragged from another app are over the element, which takes them if they are dropped, for showing it would.

func (Element) Fill

func (_handle Element) Fill() Element

Fill makes the element as large as its parent's content.

func (Element) FillHeight

func (_handle Element) FillHeight() Element

FillHeight makes the element as tall as its parent's content.

func (Element) FillWidth

func (_handle Element) FillWidth() Element

FillWidth makes the element as wide as its parent's content.

func (Element) Fit

func (_handle Element) Fit(f Fit) Element

Fit sets how an Image fills its box.

func (Element) FixedLineHeight

func (_handle Element) FixedLineHeight(v float32) Element

FixedLineHeight sets the height of lines of text in DIPs, whatever the font size, as for rows of text that line up with a grid.

func (Element) Focus

func (_handle Element) Focus() Element

Focus gives the element the keyboard focus. Called in every frame, it keeps it there; AutoFocus gives it once.

func (Element) FocusBind

func (e Element) FocusBind(field any, value any) Element

FocusBind binds desired focus to a comparable value in an app-owned field. Assign another value to request that control; its request waits while hidden. User focus changes update the field when no request is waiting. The field holds desired focus: use FocusedValue to read actual focus while a request waits. Each window should use its own field. Values must be unique per field.

func (Element) FocusGroup

func (_handle Element) FocusGroup(o Orientation) Element

FocusGroup makes the elements inside the element that take the focus one stop of Tab, as the controls of a toolbar, a radio group or a tab list are: Tab moves the focus into the group, to the element of it that had it last (else the radio button or tab chosen, else the first), and on out of it; the arrows that o names move it among them, round from the last to the first, and Home and End to the first and the last. An element inside that takes those keys itself, as a slider or a text input does, keeps them. Groups inside a group are part of it.

func (Element) FocusRing

func (_handle Element) FocusRing(show bool) Element

FocusRing sets whether Golet rings the element when it has the keyboard focus from the keyboard, as it does by default. Widgets that ring a part of themselves instead, as a check box its box, turn it off and draw their own with Painter.FocusRing while FocusVisible.

func (Element) FocusVisible

func (_handle Element) FocusVisible() bool

FocusVisible reports whether the element has the keyboard focus and should show it, because it came from the keyboard.

func (Element) FocusWithin

func (_handle Element) FocusWithin() bool

FocusWithin reports whether the element or one of its descendants has the keyboard focus.

func (Element) Focusable

func (_handle Element) Focusable() Element

Focusable lets the element take the keyboard focus, by a click or Tab.

func (Element) Focused

func (_handle Element) Focused() bool

Focused reports whether the element has the keyboard focus.

func (Element) Font

func (_handle Element) Font(family string) Element

Font sets the font family, a comma-separated list: the first family the system or the app has draws the text, and the others, in order, what it lacks, before the system's choice. "monospace" and "system-ui" are the system's own fonts.

func (Element) FontFeatures

func (_handle Element) FontFeatures(features ...string) Element

FontFeatures turns on OpenType features of the font, by tag, or sets them with tag=value:

ui.Textf(c, "%d items", n).FontFeatures("tnum")   // digits of one width
ui.Text(c, "office").FontFeatures("liga=0")       // no ligatures

A font without a feature ignores it.

func (Element) FontSize

func (_handle Element) FontSize(v float32) Element

FontSize sets the size of text in DIPs, for the element's text and its descendants'.

func (Element) FontWeight

func (_handle Element) FontWeight(w int) Element

FontWeight sets the weight of text from 100 (thin) to 900 (black).

func (Element) Gap

func (_handle Element) Gap(v float32) Element

Gap puts space between children, and between the lines of a wrapping container or the tracks of a grid.

func (Element) GapX

func (_handle Element) GapX(v float32) Element

GapX sets the horizontal space between children, lines or columns.

func (Element) GapY

func (_handle Element) GapY(v float32) Element

GapY sets the vertical space between children, lines or rows.

func (Element) Gradient

func (_handle Element) Gradient(from Color, to Color, angle float32) Element

Gradient fills the element with a linear gradient from one color to another, at angle degrees clockwise from upwards as in CSS: 180 goes from top to bottom, 90 from left to right.

func (Element) Grayscale

func (_handle Element) Grayscale() Element

Grayscale draws the element's image, or icon, in shades of gray.

func (Element) Grid

func (_handle Element) Grid() Element

Grid lays the children out in a grid, as the function Grid does.

func (Element) GridRows

func (_handle Element) GridRows(n int) Element

Rows gives the grid n rows of equal height, Fr(1) each.

func (Element) Grow

func (_handle Element) Grow(f float32) Element

Grow gives the element a share f of the free space along its parent's main axis: Grow(1) on one child makes it take all of it. Like CSS flex: f, the element then starts from no size (unless Basis says otherwise) and may shrink below its content in a column, which suits a list or editor filling the rest of a window.

func (Element) HandleInput

func (_handle Element) HandleInput(fn func(ev InputEvent) bool) Element

HandleInput has fn take the element's input as it comes, on the main thread, before the next frame is built: keys, text and edit commands while the element has the keyboard focus, the pointer pressed on it, moving over it, scrolling or pinching over it. fn reports whether it took the event; one it leaves goes on as it would without fn, to shortcuts, Tab, context menus and scroll containers. Keys that the window or an element around the focus handles as a Shortcut go to the shortcut first. A frame follows the events fn takes.

It is for widgets that need every key as it is pressed, such as a terminal, or the scrolling and pinching over them, such as a chart that zooms and pans; most widgets ask about their input as they are built instead (Clicked, Shortcut, Dragged).

func (Element) HandleTextInput

func (_handle Element) HandleTextInput(client TextInputClient) Element

HandleTextInput connects an element to the system's text-input services. Pair it with HandleInput for keys, pointer selection and Edit-menu commands, and Draw for rendering. It adds focus and the text cursor without creating a text buffer, formatting UI or undo history. A nil client disconnects it. Existing TextInput/TextArea widgets and TextCaret handlers are unchanged.

func (Element) Height

func (_handle Element) Height(v float32) Element

Height sets the height in DIPs.

func (Element) HeightPercent

func (_handle Element) HeightPercent(p float32) Element

HeightPercent sets the height as a percentage of the parent's.

func (Element) Highlighted

func (_handle Element) Highlighted() bool

Highlighted reports whether an option of a select is the one the pointer or the arrows are on.

func (Element) Hovered

func (_handle Element) Hovered() bool

Hovered reports whether the pointer is over the element. While the pointer presses an element, the elements it was over as the press began, as those around the element pressed, stay hovered as long as it is over them, as in CSS, and the others hover no more: a button that shows over a row stays as it is pressed, and dragging over other elements does not light them up.

func (Element) ID

func (_handle Element) ID() uint64

ID returns the element's identity, stable from frame to frame.

func (Element) InView

func (_handle Element) InView() bool

InView reports whether some of the element showed in the window in the frame before, within the scroll containers and clips around it: to animate it in as it scrolls into view, as Motion's whileInView.

func (Element) InputMethod

func (_handle Element) InputMethod(on bool) Element

InputMethod sets whether the system's input methods compose text for the element while it has the keyboard focus, as they do by default for one that takes text (HandleTextInput, TextCaret). Turned off, keys type the characters of the keyboard's layout, which come as InputText, and nothing is composed: a mode that reads letters as commands, as Vim's normal mode, gets j as j with a Chinese input method on, as Neovide and winit's set_ime_allowed(false) have it. Browsers cannot turn input methods off, and compose still.

func (Element) InsetShadow

func (_handle Element) InsetShadow(x float32, y float32, blur float32, spread float32, c Color) Element

InsetShadow adds an inner box shadow, as CSS's box-shadow: inset: offset by x and y, blurred by blur and grown inward by spread DIPs. It shows only inside the box's padding edge, within its border and rounded corners, above the background and below the content. Inner shadows stack in the order they are added, as outer ones do.

func (Element) Invisible

func (_handle Element) Invisible() Element

Invisible hides the element and its children, which keep their room in the layout but draw nothing and take neither the pointer nor the focus, as CSS's visibility: hidden does.

func (Element) IsDisabled

func (_handle Element) IsDisabled() bool

IsDisabled reports whether the element or an ancestor is disabled.

func (Element) Italic

func (_handle Element) Italic() Element

Italic sets an italic font.

func (Element) ItemKey

func (e Element) ItemKey(key func(int) any) Element

func (Element) Jump

func (_handle Element) Jump(key any, value float32) float32

Jump sets the value animated under key to value at once, as a drag moves it under the pointer, and returns it. The value's velocity follows the jumps from frame to frame, so that a spring taking over from the last (AnimateTo) keeps going the way it went.

func (Element) Justify

func (_handle Element) Justify(a Align) Element

Justify places the children along the main axis.

func (Element) JustifyItems

func (_handle Element) JustifyItems(a Align) Element

JustifyItems places the children of a grid in their cells horizontally: Stretch (the default), Start, Center or End. AlignItems places them vertically.

func (Element) JustifySelf

func (_handle Element) JustifySelf(a Align) Element

JustifySelf places the element in its grid cell horizontally, overriding its grid's JustifyItems.

func (Element) KeepFocus

func (_handle Element) KeepFocus() Element

KeepFocus leaves the keyboard focus where it is while the element, or what is inside it, is pressed: the popups and bars of a control that keeps typing while the user picks in them, as a combobox's options or a code editor's completions and find buttons.

func (Element) Key

func (e Element) Key(key any) Element

Key keys a container before its children or local state are built. For a stateful control, use Context.Key before construction instead.

func (Element) Keyframes

func (_handle Element) Keyframes(key any, frames []Keyframe, options ...KeyframeOptions) float32

Keyframes plays a sequence, holding its last value when done. It starts on the first call, with the first frame's value. Keep the element and key stable, and change Run when changing the sequence. Only active playback asks for animation frames. Reduced motion completes playback at its final value, including when the preference changes mid-sequence.

func (Element) Label

func (_handle Element) Label(s string) Element

Label names the element for assistive technology and for finding it in tests, when its text does not.

func (Element) Lang

func (_handle Element) Lang(tag string) Element

Lang sets the language of the element's text, and of the text of the elements inside it, as a BCP 47 tag, as HTML's lang attribute does: the system's text stack draws the glyphs of that language, as the Han characters Chinese and Japanese draw apart, and falls back to its fonts. Text is in the language the app shows (golet.App.Locale) unless told otherwise: a Japanese quote in a Chinese app,

ui.Text(c, "直").Lang("ja")

"" takes the language of the elements around it. Browsers draw text in the page's language whatever the element's.

func (Element) LayoutBounds

func (_handle Element) LayoutBounds() Rect

LayoutBounds returns the previous frame's border box before transforms, in the layout's window coordinates. Draw callbacks use these coordinates.

func (Element) Left

func (_handle Element) Left(v float32) Element

func (Element) LeftPercent

func (_handle Element) LeftPercent(p float32) Element

func (Element) LetterSpacing

func (_handle Element) LetterSpacing(v float32) Element

LetterSpacing adds v DIPs after every character of text, or tightens it with a negative v, as for labels in capitals.

func (Element) Level

func (_handle Element) Level(n int) Element

Level tells assistive technology the rank of a heading, from 1 for the highest, or how deep an item of a tree is, from 1 at the top.

func (Element) LineHeight

func (_handle Element) LineHeight(m float32) Element

LineHeight sets the height of lines of text as a multiple of the font size.

func (Element) LinearGradient

func (_handle Element) LinearGradient(g LinearGradient) Element

LinearGradient fills the element with a gradient, of which Gradient sets only the colors and the angle.

func (Element) Lines

func (_handle Element) Lines(min int, max int) Element

Lines makes a text area as high as its text, wrapped at its width, from min lines up to max, past which it scrolls, as a message field grows with what is typed: TextArea(c, &draft).Lines(1, 8). Without it, a text area is as high as its paragraphs, three lines at least, unless given a height.

func (Element) LocalToWindow

func (_handle Element) LocalToWindow(x float32, y float32) (float32, float32)

LocalToWindow maps a point in the previous frame's border box to the window.

func (Element) Loop

func (_handle Element) Loop(key any, period time.Duration, ease Easing) float32

Loop returns the progress of an animation that starts over every period, from 0 to 1 along ease, and keeps frames coming while the element is built; key tells apart the animations of the element. A spinner turns with Loop("spin", time.Second, ui.Linear) * 360, and a placeholder pulses with an opacity of 0.5 + 0.5*Loop("pulse", d, ui.Bounce(ui.EaseInOut)).

func (Element) Margin

func (_handle Element) Margin(v ...float32) Element

Margin sets the space around the element, as Padding does. Auto margins take the free space on their side.

func (Element) MarginEnd

func (_handle Element) MarginEnd(v float32) Element

func (Element) MarginStart

func (_handle Element) MarginStart(v float32) Element

MarginStart and MarginEnd set the margin on the side lines start and on the other, as PaddingStart does: Auto takes the free space there, so that a Row's child with MarginStart(ui.Auto) goes to its end.

func (Element) MarginX

func (_handle Element) MarginX(v float32) Element

MarginX sets the left and right margins.

func (Element) MarginY

func (_handle Element) MarginY(v float32) Element

MarginY sets the top and bottom margins.

func (Element) Material

func (e Element) Material(m Material) Element

func (Element) MaxHeight

func (_handle Element) MaxHeight(v float32) Element

func (Element) MaxHeightPercent

func (_handle Element) MaxHeightPercent(p float32) Element

func (Element) MaxLines

func (_handle Element) MaxLines(n int) Element

MaxLines shows at most n lines of the element's text, ending it with an ellipsis.

func (Element) MaxWidth

func (_handle Element) MaxWidth(v float32) Element

func (Element) MaxWidthPercent

func (_handle Element) MaxWidthPercent(p float32) Element

func (Element) MaximizeButton added in v0.1.8

func (_handle Element) MaximizeButton() Element

MaximizeButton marks the element as the window's maximize button, which the view draws in a window with a hidden title bar without the system's (golet.WindowOptions.HideWindowButtons): on Windows 11, holding the pointer over it shows the snap layouts, as over the system's. It takes the pointer as any element does, and the view maximizes the window when it is clicked (golet.Window.Maximize). The first such element of a frame counts; elsewhere it does nothing.

func (Element) Menu

func (_handle Element) Menu(build func(m *Menu)) Element

Menu makes the element a menu button: it opens a menu below it, which build fills with items, as the pointer goes down on it, as a pop-up button does, and for Enter, Space or Down while it has the focus. It takes the focus. build runs when the menu opens, and again in the frame after an item was chosen, where the item's Chosen reports it, as for ContextMenu. MenuButton is a button with a menu:

more := ui.ButtonBase(c).Label("More").Padding(4).Radius(6)
more.Children(func() { ui.Icon(c, moreIcon).Size(16, 16) })
more.Menu(func(m *ui.Menu) {
	if m.Item("Duplicate").Chosen() {
		app.duplicate()
	}
})

func (Element) MinHeight

func (_handle Element) MinHeight(v float32) Element

func (Element) MinHeightPercent

func (_handle Element) MinHeightPercent(p float32) Element

func (Element) MinWidth

func (_handle Element) MinWidth(v float32) Element

MinWidth, MinHeight, MaxWidth and MaxHeight bound the size in DIPs.

func (Element) MinWidthPercent

func (_handle Element) MinWidthPercent(p float32) Element

MinWidthPercent, MinHeightPercent, MaxWidthPercent and MaxHeightPercent bound the size by a percentage of the parent's.

func (Element) Mixed

func (_handle Element) Mixed() Element

Mixed tells assistive technology that the element, a check box, is partly on, as one checking a group whose boxes differ.

func (Element) Modal

func (_handle Element) Modal() Element

Modal makes the element, built in an Overlay, a dialog's backdrop, as DialogBase's: while it shows, the focus moves into it, Tab goes round the elements inside it, the window's shortcuts built outside it wait, and assistive technology sees it and what shows above it alone, as what is behind it is inert. Build the dialog inside it.

func (Element) NoWrap

func (_handle Element) NoWrap() Element

NoWrap keeps each line of the element's text whole, breaking it only at newlines, even where it overflows the element.

func (Element) OnChange

func (e Element) OnChange(fn func()) Element

OnChange runs after input changes the bound value, before rebuilding the view. The callback can commit a derived value local to this build pass.

func (Element) OnClick

func (e Element) OnClick(fn func()) Element

OnClick runs after construction and bound-value input.

func (Element) OnPaste

func (_handle Element) OnPaste(fn func(text string) bool) Element

OnPaste has fn see a paste into a text input, by Cmd+V, Ctrl+V or a Paste menu item, before it is inserted, on the main thread as the paste comes: text is the clipboard's text, empty when it holds none, as with an image, which the app reads from the clipboard itself. fn reports whether it took the paste; a paste taken changes nothing, its selection and undo history included, as when a web page prevents a paste's default and attaches a large block instead of inserting it. Like ReadOnly, it holds for the input that comes until the next frame.

func (Element) OnShortcut

func (e Element) OnShortcut(mods Modifiers, key Key, fn func()) Element

OnShortcut declares a key handler within the element's focus subtree.

func (Element) OnSubmit

func (e Element) OnSubmit(fn func()) Element

OnSubmit runs after bound-value input handles a submission gesture, before rebuilding the view.

func (Element) OnTextKey

func (_handle Element) OnTextKey(fn func(k TextKey) bool) Element

OnTextKey has fn see a key pressed in the text input before the input takes it, on the main thread as the key comes, with the text typed before it in place, as AppKit's doCommandBySelector and a web page's keydown on a text field: Enter that sends a message, Up that edits the last one, Tab that accepts a completion, Escape that cancels, Cmd+Enter. fn reports whether it took the key; one taken changes nothing but what fn sets: a text area inserts no newline, a single-line input does not submit, Tab does not move the focus. One left goes on as it would without fn.

fn sees the keys that type no text: those with Cmd or Ctrl, and Enter, Tab, Escape, Backspace, Delete, the arrows and the other keys that move the caret, as pressed (macOS's Control keys that move the caret too). While an input method composes, its keys are its own. Keys that the window or an element around the focus handles as a Shortcut go to the shortcut first, as with HandleInput, unless the input edits with them, as with Enter and the arrows. Like ReadOnly, OnTextKey holds for the input that comes until the next frame.

fn runs between frames, where an Element kept from the view is no longer valid: it reads and replaces the text through k instead, as a chat composer sends with Enter, clears what it sent, and breaks the line with Shift+Enter:

ui.TextArea(c, &app.draft).OnTextKey(func(k ui.TextKey) bool {
	if k.Key != ui.KeyEnter || k.Mods != 0 {
		return false // Shift+Enter breaks the line
	}
	app.send(k.Text())
	k.SetText("")
	return true
})

func (Element) Opacity

func (_handle Element) Opacity(o float32) Element

Opacity makes the element and its children translucent.

func (Element) OverlayShortcut

func (_handle Element) OverlayShortcut(mods Modifiers, key Key) bool

OverlayShortcut reports whether the key with exactly the modifiers mods was pressed for the element, an overlay, which gets the keys the focused element and those around it leave, wherever the focus is: the overlay built last first, so that Escape closes the one on top. Overlays close with it, as PopoverBase and DialogBase do:

if panel.OverlayShortcut(0, ui.KeyEscape) {
	app.open = false
}

func (Element) Padding

func (_handle Element) Padding(v ...float32) Element

Padding sets the space inside the element's edges, CSS style: all sides, vertical and horizontal, or top, right, bottom and left.

func (Element) PaddingEnd

func (_handle Element) PaddingEnd(v float32) Element

func (Element) PaddingStart

func (_handle Element) PaddingStart(v float32) Element

PaddingStart sets the padding on the side lines start: the left, or the right of an element laid out right to left, as CSS's padding-inline-start does. PaddingEnd sets the other side's.

func (Element) PaddingX

func (_handle Element) PaddingX(v float32) Element

PaddingX sets the left and right padding.

func (Element) PaddingY

func (_handle Element) PaddingY(v float32) Element

PaddingY sets the top and bottom padding.

func (Element) PassThrough

func (_handle Element) PassThrough() Element

PassThrough lets the pointer reach what is under the element.

func (Element) Password

func (_handle Element) Password() Element

Password hides what a text input holds, in the frames that call it: an input that stops calling it shows its text again, as a field's eye button does. It does nothing to a text area: as on every platform, only single-line fields hide their text.

func (Element) Perspective

func (_handle Element) Perspective(distance float32) Element

Perspective sees the element's transform in 3D from distance DIPs in front of its origin (Perspective).

func (Element) Placeholder

func (_handle Element) Placeholder(s string) Element

Placeholder shows s in an empty text input.

func (Element) PointerPosition

func (_handle Element) PointerPosition() (float32, float32, bool)

PointerPosition returns the pointer's position relative to the element's box and whether it is over the element. Elements asking for it get a frame whenever the pointer moves over them.

func (Element) Pressed

func (_handle Element) Pressed() bool

Pressed reports whether the element is being pressed with the pointer, unless it is disabled.

func (Element) PressedOutside

func (_handle Element) PressedOutside() bool

PressedOutside reports whether the pointer went down since the last frame outside the element: on neither it, nor what it holds, nor the element it is attached to (AttachTo), nor the overlays attached to elements inside it, as the popover of one of its buttons. A popover closes then, the press going on to what is under the pointer, as PopoverBase does. The last press decides: one on the button opening a popover after a press elsewhere, as on a web view's page, in the same frame, keeps it open.

func (Element) Radius

func (_handle Element) Radius(r ...float32) Element

Radius rounds the corners: one radius for all, or top-left, top-right, bottom-right and bottom-left.

func (Element) Range

func (_handle Element) Range(lo float64, hi float64, value float64) Element

Range tells assistive technology the range and the value of a slider, progress bar, meter or stepper of your own: value, from lo to hi. Step tells it how far the keys move the value.

func (Element) ReadOnly

func (_handle Element) ReadOnly(on bool) Element

ReadOnly makes a text input show its text without letting the user change it: the text can still be selected and copied, from the keyboard too, as it takes the focus, without a caret; assistive technology reads it as read-only.

func (Element) Ref

func (e Element) Ref(r *Ref) Element

Ref is an alias for Bind.

func (Element) Reverse

func (_handle Element) Reverse() Element

Reverse lays the children out in the other direction: a Row from right to left, a Column from bottom to top, as CSS's row-reverse and column-reverse do. Justify's Start is then the right or the bottom.

func (Element) Right

func (_handle Element) Right(v float32) Element

func (Element) RightClicked

func (_handle Element) RightClicked() bool

RightClicked reports a click with the secondary button, as for a context menu.

func (Element) RightPercent

func (_handle Element) RightPercent(p float32) Element

func (Element) Role

func (_handle Element) Role(r Role) Element

Role sets what the element is to assistive technology, for an element drawn as a widget it is not built from, such as a custom toggle.

func (Element) Rotate

func (_handle Element) Rotate(degrees float32) Element

Rotate rotates an element clockwise around its transform origin, which changes no layout sizes. An Icon keeps turning its SVG artwork around its center, as a spinner does:

spin := ui.Icon(c, loader)
spin.Rotate(spin.Loop("spin", time.Second, ui.Linear) * 360)

Use Transform(Rotation(degrees)) to rotate an icon's entire border box.

func (Element) RotateX

func (_handle Element) RotateX(degrees float32) Element

RotateX turns the element in 3D around the horizontal axis through its origin, after its existing transform, as RotationX: follow it with Perspective to see it in depth.

card.RotateX(30).Perspective(800)

func (Element) RotateY

func (_handle Element) RotateY(degrees float32) Element

RotateY turns the element in 3D around the vertical axis through its origin, after its existing transform, as RotationY: a card turning over shows its back past 90 degrees, mirrored.

card.RotateY(flip * 180).Perspective(800)

func (Element) Row

func (_handle Element) Row() Element

Row lays the children out from left to right.

func (Element) RowDoubleClicked

func (_handle Element) RowDoubleClicked() bool

RowDoubleClicked reports, while a row of a List or a Table builds, that the row was double-clicked since the last frame with the pointer over the element: a cell sees its row's double click this way and leaves the click to the row, which chooses, where DoubleClicked would take it.

ui.Table(c, &app.list, cols, len(app.rows), func(row, col int) {
	cell := ui.Box(c).FillWidth().Children(func() { ui.Text(c, app.rows[row][col]) })
	if cell.RowDoubleClicked() {
		app.edit(row, col)
	}
})

func (Element) RowSpan

func (_handle Element) RowSpan(n int) Element

RowSpan makes the element span n rows of its grid, or, for a negative n, every row from its start to the last the grid sets.

func (Element) RowStart

func (_handle Element) RowStart(n int) Element

RowStart puts the element in row n of its grid, counting from 1.

func (Element) RowTracks

func (_handle Element) RowTracks(tracks ...Track) Element

RowTracks sets the grid's first rows; those it adds after fit their content.

func (Element) RowWidth

func (_handle Element) RowWidth(w float32) Element

RowWidth makes the rows of a List at least w DIPs wide, as the columns of a table ask: where they are wider than the list, it scrolls sideways too, and its rows grow to its width where they are not. A header above the rows goes with them through ScrollWith:

head := ui.Row(c).Clip().Padding(0, 8).Children(app.columnTitles)
list := ui.List(c, &app.rows, n).Padding(0, 8).RowWidth(app.columnsWidth())
list.Rows(app.row)
head.ScrollWith(list)

func (Element) Rows

func (e Element) Rows(row func(ListRow)) Element

func (Element) Scale

func (_handle Element) Scale(x float32, y float32) Element

Scale scales the element after its existing transform, around its origin.

func (Element) ScrollIntoView

func (_handle Element) ScrollIntoView() Element

ScrollIntoView scrolls the containers around the element as little as shows it, once the frame is laid out: an element added in this frame comes into view with it. Call it in the frame it should come into view, as when it is added or chosen: in every frame, it would keep the user from scrolling it away.

func (Element) ScrollWith

func (_handle Element) ScrollWith(scroller Element) Element

ScrollWith moves the element's content sideways as far as scroller, a scroll container, scrolls its own, as a table's header goes with its rows. Clip the element, so that what goes out of it does not show.

func (Element) ScrollbarInsets

func (_handle Element) ScrollbarInsets(v ...float32) Element

ScrollbarInsets moves a scroll container's scroll bars in from its edges, CSS style as Padding: the vertical bar runs from top DIPs below its top to bottom DIPs above its bottom, right DIPs in from its right, and the horizontal bar from left to right DIPs in, bottom DIPs up. A bar keeps clear so of what floats over the content, as a toolbar the content scrolls under, which AppKit's scrollerInsets and UIKit's scroll indicator insets do:

ui.Scroll(c).Fill().Padding(64, 16, 16).ScrollbarInsets(64, 0, 0)

func (Element) Selectable

func (_handle Element) Selectable() Element

Selectable lets the user select and copy text by dragging, double-clicking a word, triple-clicking a line, or using Shift with the arrows. Its context menu has Copy and Select All; Cmd+C copies the selection.

On a container, its Text and RichText descendants share one selection. Copy joins their selected text with newlines, in the order they were built. Nested Selectable containers have independent selections. Text inside controls, such as buttons and text inputs, keeps the control's interaction. Unselectable excludes a subtree. On a Text or RichText alone, the selection stays within that paragraph. Inline elements share their paragraph's selection; set Selectable on the paragraph.

func (Element) Selected

func (_handle Element) Selected(on bool) Element

Selected shows the element as chosen among its siblings, in the accent color, as a row of a list, and tells assistive technology it is.

func (Element) SelectedTexts

func (_handle Element) SelectedTexts() []SelectedText

SelectedTexts returns the parts of the paragraphs that the selection of a Selectable container holds, in the order they were built, or none, as of the last frame: to copy them otherwise, as a context menu's item does.

func (Element) Selection

func (e Element) Selection(selection Selector) Element

func (Element) SelectionColor

func (_handle Element) SelectionColor(c Color) Element

SelectionColor sets the highlight of selected text in the element and the text inside it, as text on a colored bubble needs one that shows on it; the theme's Selection is the highlight elsewhere.

func (Element) SetChanged

func (_handle Element) SetChanged() Element

SetChanged reports the element's value as changed in this build pass, as a widget of your own whose input changed what it edits: Changed returns true for it, as for the widgets' own.

func (Element) SetTextSelection

func (_handle Element) SetTextSelection(start int, end int) Element

SetTextSelection selects the runes of a text input from start to end, or puts the caret at start when they are equal, and scrolls it into view: the caret after a word the app completed. The offsets are kept within the text.

func (Element) Settled

func (_handle Element) Settled(key any) bool

Settled reports whether the value animated under key, by AnimateTo, Animate, Spring or Keyframes, rests at its target in this frame: true for an unknown key.

func (Element) Shadow

func (_handle Element) Shadow(x float32, y float32, blur float32, spread float32, c Color) Element

Shadow adds a box shadow, offset by x and y, blurred by blur and grown by spread DIPs. As CSS's box-shadow, it shows only outside the box: a translucent background does not show it through.

func (Element) Shortcut

func (_handle Element) Shortcut(mods Modifiers, key Key) bool

Shortcut reports whether the key with exactly the modifiers mods was pressed while the element or one of its descendants had the focus. The innermost element handling a key gets it; a disabled one handles none.

func (Element) Shrink

func (_handle Element) Shrink(f float32) Element

Shrink sets how much the element gives up when its siblings do not fit (1 by default, 0 never).

func (Element) SingleLine

func (_handle Element) SingleLine() Element

SingleLine keeps the element's text on one line, ending it with an ellipsis when it does not fit.

func (Element) Size

func (_handle Element) Size(w float32, h float32) Element

Size sets the width and height in DIPs.

func (Element) Skew

func (_handle Element) Skew(x float32, y float32) Element

Skew slants the element after its existing transform, around its origin, by x degrees along the horizontal axis and y along the vertical.

func (Element) Spring

func (_handle Element) Spring(key any, target float32, options ...SpringOptions) float32

Spring returns a value following target with a spring, as AnimateTo does with Animation{Spring: options}: Smooth's spring without options.

func (Element) Start

func (_handle Element) Start(v float32) Element

Start and End place an Absolute element from the side lines start and from the other, as Left and Right do, as CSS's inset-inline-start and inset-inline-end: from the left and the right, or the right and the left right to left. On an element in its parent's layout, they move it as relative positioning does.

func (Element) StartPercent

func (_handle Element) StartPercent(p float32) Element

StartPercent and EndPercent place the element as Start and End do, by a percentage of the parent's width.

func (Element) Step

func (_handle Element) Step(step float64) Element

Step makes the values of a slider lo and the multiples of step from it, which the arrows move between, as a StepSlider's. Of a range of your own (Range), it tells assistive technology how far the keys move the value.

func (Element) Strikethrough

func (_handle Element) Strikethrough() Element

Strikethrough strikes text through.

func (Element) Stripes

func (_handle Element) Stripes(c Color, width float32, gap float32, angle float32) Element

Stripes draws stripes of c over the background, width DIPs wide with gap DIPs between them, running at angle degrees clockwise from upwards: 0 draws vertical stripes, 90 horizontal ones, and 45 slanting ones like slashes, as to mark what is unavailable.

func (Element) Submitted

func (_handle Element) Submitted() bool

Submitted reports whether Enter was pressed in a single-line text input in this build pass.

func (Element) TextAlign

func (_handle Element) TextAlign(a Align) Element

TextAlign aligns the lines of text: Start, Center or End.

func (Element) TextAnchorCaret

func (_handle Element) TextAnchorCaret() (int, int)

TextAnchorCaret returns the selection of a text input as offsets in runes into its text, from where it was started to its caret: the anchor is after the caret when the selection was made backwards.

func (Element) TextBackground

func (_handle Element) TextBackground(c Color) Element

TextBackground fills the lines of text behind it with c, as a highlight.

func (Element) TextCaret

func (_handle Element) TextCaret(r Rect) Element

TextCaret has the element take text from the system's input methods while it has the keyboard focus, with their composition at r, the caret, relative to the element's box: candidate windows show there. Its InputText and Compose events (HandleInput) bring the text.

func (Element) TextColor

func (_handle Element) TextColor(c Color) Element

TextColor sets the color of text.

func (Element) TextRanges

func (_handle Element) TextRanges(ranges ...TextRange) Element

TextRanges styles runs of a text input's text, in the frames that call it. Ranges may overlap and nest, as the attributes of an attributed string do: where they do, each of Color and Weight is that of the last range given that sets it, across the calls of the frame. They follow the text as it is: an app that finds them in the text finds them again as it changes. A password shows none; an input method's composition shows unstyled between them.

func (Element) TextSelection

func (_handle Element) TextSelection() (int, int)

TextSelection returns the selection of a text input as offsets in runes into its text, the caret where start equals end, as the app reads it to complete the word being typed.

func (Element) Timeline

func (_handle Element) Timeline(key any, o TimelineOptions) *Timeline

Timeline returns the timeline the element keeps under key, playing it as o says. Every tween added to it shares one playhead, and returns the value it shows in this frame.

card := ui.Column(c)
tl := card.Timeline("intro", ui.TimelineOptions{Run: app.opened})
x := tl.Tween(ui.Tween{From: -200, To: 0, Duration: 400 * time.Millisecond})
card.Translate(x, 0)

Key tells apart the timelines of the element, as it does its Keyframes, and an element asks for each of its timelines once per build. Play the timeline again, or a changed one, by changing o.Run. The *Timeline is valid while the view builds this frame.

While the desktop asks for less motion (Preferences.ReduceMotion), a timeline that would play is at once where it would come to rest, but Seek, Progress and Paused still put and hold its playhead, as a drag still moves a Draggable element. DisableAnimations does not change a timeline, which plays on its own, as Keyframes do: jump it with Seek.

func (Element) Tooltip

func (_handle Element) Tooltip(s string) Element

Tooltip shows s by the element when the pointer rests on it, or the keyboard focus comes to it, as TooltipBase does: above the element, centered, or below it where there is no room above. It describes the element to assistive technology where Description does not.

func (Element) Top

func (_handle Element) Top(v float32) Element

Top, Right, Bottom and Left place an Absolute element. On an element in its parent's layout, they move it from where the layout put it, as CSS's relative positioning does, without moving its siblings.

func (Element) TopPercent

func (_handle Element) TopPercent(p float32) Element

TopPercent, RightPercent, BottomPercent and LeftPercent place the element as Top, Right, Bottom and Left do, by a percentage of the parent's height or width.

func (Element) TrackLines

func (_handle Element) TrackLines(l *TextLines) Element

TrackLines keeps in l where the text area lays out its lines.

func (Element) TrackScroll

func (_handle Element) TrackScroll(s *ScrollState) Element

TrackScroll keeps the scrolling of a scroll container (Scroll, ScrollHorizontal, ScrollBoth, List) in *s: the container shows its content from s.X and s.Y, and writes there as the user scrolls it. The app reads where it is, scrolls it by setting them, and keeps a place with a ScrollState of its own for each page the container shows.

// A log that follows its end, unless the user scrolled up from it.
if app.log.Y >= app.log.MaxY {
	app.log.Y = math.MaxFloat32
}
ui.Scroll(c).TrackScroll(&app.log).Children(app.lines)

A List keeps its place by its rows instead, and scrolls to a row with its ListState.

func (Element) Transform

func (_handle Element) Transform(t Transform) Element

Transform sets the element's visual transform. Its origin is the center of its border box unless TransformOrigin changes it.

func (Element) TransformOrigin

func (_handle Element) TransformOrigin(x float32, y float32) Element

TransformOrigin sets the origin as fractions of the border box: (0,0) is the top-left and (0.5,0.5) the center. Values outside the box are allowed. Translation does not depend on the origin.

func (Element) Transition

func (_handle Element) Transition(t ElementTransition) Element

Transition animates the element as t asks. The element needs the same ID from frame to frame: a Key, or the same place among its siblings. Elements that the change moves as well need a Transition of their own to move smoothly, the same one to move in step with it, as the rows of a list:

for _, it := range app.items {
	ui.Row(c).Key(it.ID).Transition(rowTransition).Children(func() {
		ui.Text(c, it.Title)
	})
}

Changes made by resizing the window do not animate. While the desktop asks for less motion (Preferences.ReduceMotion), nothing moves: colors still change smoothly, and an Enter or Exit that fades without collapsing fades in place.

func (Element) Transitioning

func (_handle Element) Transitioning() bool

Transitioning reports whether the element's Transition was moving it, or changing its colors, or its pose (AnimatePose) or Draggable was moving it, in the frame before: false once it is where it goes.

func (Element) Translate

func (_handle Element) Translate(x float32, y float32) Element

Translate moves the element after its existing transform.

func (Element) Underline

func (_handle Element) Underline() Element

Underline underlines text.

func (Element) Unselectable

func (_handle Element) Unselectable() Element

Unselectable excludes a paragraph or container subtree from a surrounding Selectable container. A Selectable container nested inside it can provide a selection of its own. For inline elements, set it on their paragraph.

func (Element) Valid

func (e Element) Valid() bool

Valid reports whether the element belongs to the active build pass. Checking validity does not trigger expired-handle diagnostics.

func (Element) Value

func (_handle Element) Value(s string) Element

Value sets what assistive technology reads as the element's value, as the choice a button opening a popup shows.

func (Element) Velocity

func (_handle Element) Velocity(key any) float32

Velocity returns how fast, in its units per second, the value animated under key goes in this frame: zero for one at rest or unknown.

func (Element) Vertical

func (_handle Element) Vertical() Element

Vertical makes a SliderBase go up, from lo at the bottom of its content box to hi at the top, and tells assistive technology so. Pad it by half the thumb's height, rather than its width. Slider, drawn across, stays so.

func (Element) WavyUnderline

func (_handle Element) WavyUnderline() Element

WavyUnderline underlines text with a wave, as spell checkers mark words.

func (Element) Width

func (_handle Element) Width(v float32) Element

Width sets the width in DIPs.

func (Element) WidthPercent

func (_handle Element) WidthPercent(p float32) Element

WidthPercent sets the width as a percentage of the parent's.

func (Element) WindowToLocal

func (_handle Element) WindowToLocal(x float32, y float32) (float32, float32, bool)

WindowToLocal maps a window point into the previous frame's border box. ok is false for singular transforms, which take no pointer input.

func (Element) Wrap

func (_handle Element) Wrap() Element

Wrap starts a new line of children when they do not fit.

func (Element) WrapReverse

func (_handle Element) WrapReverse() Element

WrapReverse wraps the children onto lines that stack the other way: up in a Row, to the left in a Column.

type ElementTransition

type ElementTransition struct {
	// Duration is how long a change takes: 200 ms when zero.
	Duration time.Duration
	// Ease is how the element goes, as for AnimateWith: EaseOut when nil.
	Ease Easing
	// Animation, if set, is how changes go instead of Duration and Ease:
	// with a spring (Snappy, …), a change on the way keeps the element
	// going as it went; with a Delay, changes wait, as the rows of a list
	// entering one after another.
	Animation *Animation
	// Position, Size and Colors choose what animates: where the element is
	// in its parent, its width and height (its content laid out at each
	// size on the way), and its background and border colors. None set
	// animates them all.
	Position, Size, Colors bool
	// Enter, if set, is where the element comes from as it appears in a
	// parent that the last frame showed: it starts there, and goes to its
	// place.
	Enter *Motion
	// Exit, if set, is where the element goes once it is no longer built,
	// while its parent still is: a copy of it, as the last frame showed
	// it, goes there under its siblings, taking neither room, the pointer
	// nor the focus, and is then gone.
	Exit *Motion
	// Match, if set, is an identity the element shares with one that the
	// frame before showed elsewhere, even in another parent, as a photo's
	// thumbnail in a grid and the photo in a detail view: the element
	// appearing comes from where that one was, at its size and in its
	// colors, as SwiftUI's matchedGeometryEffect and Motion's layoutId.
	// Use a value of a type of your own, as a struct of the photo's ID.
	Match any
}

ElementTransition animates an element (Element.Transition) from what the last frame showed to what the layout makes of it in this one: where it is in its parent, its size, and its background and border colors. Enter and Exit animate it as it appears and as it goes:

ui.Row(c).Key(item.ID).Transition(ui.ElementTransition{
	Enter: &ui.Motion{Collapse: true},
	Exit:  &ui.Motion{Collapse: true},
})

type Fit

type Fit uint8

Fit says how an image fills its element.

const (
	// Contain scales the image to fit inside the element, keeping its
	// aspect ratio.
	Contain Fit = iota
	// Cover scales the image to cover the element, cropping it.
	Cover
	// FillBox stretches the image to the element.
	FillBox
	// ScaleDown shows the image at its own size, or as Contain does where
	// that is smaller.
	ScaleDown
	// NaturalSize shows the image at its own size, centered and cropped.
	NaturalSize
)

type Font

type Font struct {
	Family   string
	Size     float32
	Weight   int
	Italic   bool
	Features string
	// Lang is the language of the text, as for Element.Lang; "" is the
	// language the app shows.
	Lang string
	// Thicken draws the glyphs with a thicker stroke, as Ghostty's
	// font-thicken: on macOS, with Core Text's font smoothing at its
	// strongest, whatever the color and the user's setting. It changes
	// nothing elsewhere.
	Thicken bool
	// Antialiased draws the glyphs without font smoothing, thinner, as
	// browsers draw text styled -webkit-font-smoothing: antialiased on
	// macOS, for drawings that match a web page's. It changes nothing
	// elsewhere.
	Antialiased bool
}

Font is a font for text a Painter draws itself (Shape): a family list as Element.Font takes it, a size in DIPs (14 when 0), a weight from 100 to 900 (400 when 0), italics, and OpenType features as Element.FontFeatures takes them, comma separated.

func (Font) Metrics

func (f Font) Metrics() FontMetrics

Metrics returns the font's metrics.

type FontFamily

type FontFamily struct {
	// Name is the family as Font and Theme take it.
	Name string
	// Monospaced is whether its regular font gives every character the
	// same advance, as a terminal's or a code editor's font setting
	// offers.
	Monospaced bool
	// Registered is whether the app registered it with RegisterFont, under
	// Name: the name it gave, or the font's own when it gave none.
	Registered bool
}

A FontFamily is a font family text can use, as FontFamilies lists it.

func FontFamilies

func FontFamilies() []FontFamily

FontFamilies lists the font families text can use, as a font setting offers them: the app's registered ones first, then the system's, each once, sorted without regard to case. A font registered under a name the app gave is listed under that name alone. Browsers do not tell what fonts they have: there the list holds the registered families alone, and a family is Monospaced once its font has loaded.

The first call asks the system for its families, which takes a while with many fonts installed (tens of milliseconds on a Mac with hundreds), without holding up the windows' text; later calls reuse that list, until RegisterFont, so fonts installed while the app runs show after a restart. It is safe from any goroutine.

type FontMetrics

type FontMetrics struct {
	Ascent, Descent, LineGap float32
}

FontMetrics are the vertical metrics of a font, in DIPs: how far its glyphs reach above and below the baseline, and the gap it leaves between lines.

type Glyph

type Glyph struct {
	// Cluster is the rune of the text the glyph's cluster starts at, and
	// Runes how many runes the cluster holds: a ligature holds several,
	// and so does a character with combining marks, whose glyphs share
	// the cluster.
	Cluster, Runes int
	// X is the left of the glyph's advance from the start of the text,
	// and Advance its width. Move X to draw the glyph elsewhere, as in the
	// cell of a grid.
	X, Advance float32
	// contains filtered or unexported fields
}

Glyph is a glyph of text that Shape placed, which Painter.Glyphs draws.

func Shape

func Shape(s string, f Font) []Glyph

Shape shapes s in font f, on one line, for Painter.Glyphs: the system's text engine finds the font, falls back to others for what it lacks, and applies ligatures and kerning. Unlike the text of elements, which ui caches by content, it caches nothing: keep the glyphs of text drawn in several frames.

type GradientStop

type GradientStop struct {
	Color Color
	At    float32
}

GradientStop is a color of a gradient (LinearGradient, ConicGradient) and its place along it, from 0 to 1, as CSS's color stops are. The gradient shows its first color before its first stop, its last after its last, and between two stops their colors blended; two stops at one place make a sharp edge. A gradient takes 32 stops at most, in sRGB.

type GridState

type GridState struct {
	Handle

	// Key returns an identity for item i, as ListState.Key does for a
	// row: the choice and the items' state follow it.
	Key func(item int) any
	// Selected, when set, lets a click choose an item, as the arrows do
	// while the grid has the keyboard focus: *Selected is the item chosen,
	// -1 for none. The grid's Changed reports a new choice, and its
	// Submitted a double click or Enter.
	Selected *int
	// Selection, when set, lets the user choose several items, held by
	// their keys, as a List's Selection: Cmd-click (Ctrl-click on Linux
	// and Windows) adds an item or takes it out, Shift-click and Shift
	// with the arrows choose those from the item last chosen, and Cmd+A
	// chooses all. Selected, set as well, is the item last chosen.
	Selection Selector
	// Label returns the text of item i: typing its first letters while
	// the grid has the focus chooses it, and assistive technology reads it
	// as the item's name.
	Label func(item int) string
	// Reorder, when set, lets the user drag items to another place in the
	// grid, as ListState.Reorder does rows: the items chosen, when the item
	// dragged is one, else that item, in order, and the item they go
	// before, the number of items for the end.
	Reorder func(items []int, to int)
	// contains filtered or unexported fields
}

GridState is the state of a GridView: how its items are told apart and chosen, as a List's rows are, and the place of its rows.

func (*GridState) ScrollIntoView

func (s *GridState) ScrollIntoView(item int)

ScrollIntoView scrolls the grid as little as shows item.

func (*GridState) ScrollTo

func (s *GridState) ScrollTo(item int, align Align)

ScrollTo scrolls the grid to show item at align, as ListState.ScrollTo does a row.

type Handle

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

Handle identifies a control across builds. Bind it to an Element on each pass. One handle may have separate bindings in several windows. Queries take a Context and read committed identity, regardless of build order. Use on the UI thread; background work uses Window.Update.

func (Handle) Bounds

func (r Handle) Bounds(c *Context) Rect

Bounds returns the control's box in the committed frame, in window DIPs. It works between builds on the UI thread; hidden or closed controls return an empty box. Use this instead of retaining an Element in input callbacks.

func (*Handle) CancelFocus

func (r *Handle) CancelFocus(window ...*Context)

CancelFocus cancels pending focus in the selected window, or every binding.

func (*Handle) Focus

func (r *Handle) Focus(window ...*Context)

Focus requests focus, waiting while the control is hidden. Supply a Context to select a window. Without one, a handle must have at most one open window. A request made before its first binding waits for that binding.

func (Handle) FocusWithin

func (r Handle) FocusWithin(c *Context) bool

func (Handle) Focused

func (r Handle) Focused(c *Context) bool

func (*Handle) OnShortcut

func (r *Handle) OnShortcut(c *Context, mods Modifiers, key Key, fn func())

OnShortcut declares an action before or after Bind. A control omitted from this pass takes no shortcut. Actions run once after bindings are complete.

func (*Handle) RequestFocus

func (r *Handle) RequestFocus(window ...*Context)

RequestFocus is an alias for Focus.

type ImageOptions

type ImageOptions struct {
	// FlipX mirrors the part left to right, FlipY top to bottom.
	FlipX, FlipY bool
	// Tint multiplies its colors and alpha, as a colored filter would;
	// zero for none.
	Tint Color
}

ImageOptions are how Painter.ImageRegion draws a part of a bitmap.

type ImageSource

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

ImageSource is what Image shows: a *Bitmap, or an *SVG in its own colors.

type InputEvent

type InputEvent struct {
	Kind InputKind
	Key  Key
	// PhysicalKey is Key by position on an ANSI US keyboard, whatever the
	// layout types: the S key is KeyS on a Cyrillic layout too, where Key
	// is KeyUnknown. KeyUnknown where the platform does not report it.
	PhysicalKey Key
	Mods        Modifiers
	Repeat      bool
	// Text of InputText, InputCompose and InputCommand, and Caret the
	// rune of an InputCompose's caret.
	Text  string
	Caret int
	// X and Y locate the pointer relative to the element's box.
	X, Y float32
	// Button is 0 for the primary button, 1 the secondary and 2 the
	// middle.
	Button int
	Clicks int
	// DX and DY are what InputScroll scrolls by, in local axes; positive DY moves the view
	// down the content.
	DX, DY  float32
	Precise bool
	// Scale is what InputZoom zooms by.
	Scale float32
	// Start and End are the runes InputSelect selects.
	Start, End int
	// Time is when the event came, by the clock of the window's frames
	// (Context.Now), which a Tester's clock is in tests.
	Time time.Time
}

InputEvent is input an element takes as it comes (HandleInput).

type InputKind

type InputKind uint8

InputKind is the kind of an InputEvent.

const (
	// InputKeyDown and InputKeyUp report a key with the modifiers held;
	// Repeat marks the auto-repeat of a key held down. A key that types
	// text comes before the text, an InputText event, on macOS and
	// Windows; on Linux, only the text comes while the element takes text
	// (TextCaret) with input methods on (InputMethod).
	InputKeyDown InputKind = iota + 1
	InputKeyUp
	// InputText is text typed, or committed by an input method.
	InputText
	// InputCompose is the composition of an input method, with its caret
	// at rune Caret; an empty Text ends it.
	InputCompose
	// InputCommand is an edit command of the menus, such as Copy of the
	// Edit menu: "copy", "cut", "paste", "pasteAndMatchStyle" (which
	// comes again as "paste" when the element doesn't take it),
	// "selectAll", "undo", "redo" or "delete", or one of the Format menu,
	// as Bold: "bold", "italic", "underline", "strikethrough",
	// "alignLeft", "alignCenter" or "alignRight".
	InputCommand
	// InputPointerDown and InputPointerUp report Button pressed or
	// released at X, Y, with Clicks the count of quick successive presses
	// (2 for a double click). Once the element takes an InputPointerDown,
	// the pointer's moves and its release come to it wherever they are,
	// and the release comes when the window loses the keyboard too.
	InputPointerDown
	InputPointerUp
	// InputPointerMove reports the pointer at X, Y, with Button held, or
	// -1 when none is.
	InputPointerMove
	// InputScroll scrolls by DX, DY DIPs at X, Y; Precise marks
	// touchpads, which scroll by pixels rather than by lines. One the
	// element leaves scrolls the scroll containers around it.
	InputScroll
	// InputSelect selects runes Start to End of the text an element
	// describes to assistive technology (Element.Access), as a screen
	// reader moves the selection of a text field of the app's own.
	InputSelect
	// InputZoom zooms by Scale at X, Y, as pinching a touchpad does: 2
	// shows the content twice as large as it was, 0.5 half as large.
	// macOS, Linux on Wayland and browsers report pinches; Windows reports
	// them as scrolling with Ctrl held, so there a touchpad's scrolling
	// with Ctrl held comes as InputZoom too, and a mouse wheel's notches
	// as InputScroll with Ctrl in Mods.
	InputZoom
)

Kinds of input.

type Key

type Key uint16

Key identifies a key. Letter and digit keys follow the keyboard layout: KeyA is the key that types an a.

type Keyframe

type Keyframe struct {
	At    time.Duration
	Value float32
	Ease  Easing
}

Keyframe is a value at At since a sequence starts. The first At must be zero, subsequent times strictly increase. Ease controls the segment arriving at this frame; nil means Linear.

type KeyframeOptions

type KeyframeOptions struct {
	// Run replays the sequence, or a changed one, when it changes: the
	// first time through, it starts from the value shown, so that
	// interrupting it does not jump.
	Run uint64
	// Repeat is how many more times the sequence plays after the first,
	// as Motion's repeat: RepeatForever for ever. Alternate plays every
	// other time backward.
	Repeat    int
	Alternate bool
	// Delay is how long the sequence holds its first value before it
	// plays, and RepeatDelay how long it holds where it got to before it
	// plays again.
	Delay, RepeatDelay time.Duration
}

KeyframeOptions controls playback.

type LinearGradient

type LinearGradient struct {
	From, To Color
	// Angle is the direction of the line, in degrees clockwise from
	// upwards: 180 goes from top to bottom, 90 from left to right.
	Angle float32
	// Start and End place From and To along the line, from 0 to 1: the
	// colors are solid before Start and after End. Both 0 mean 0 and 1.
	Start, End float32
	// Oklab mixes the colors in the Oklab color space, whose midpoints keep
	// the colors' lightness and saturation, instead of in sRGB, as CSS's
	// "in oklab" does.
	Oklab bool
	// Stops, unless empty, are the gradient's colors in place of From and
	// To (and Start and End), at their places along the line from 0 to 1,
	// in order:
	//
	//	ui.LinearGradient{Angle: 90, Stops: []ui.GradientStop{{red, 0}, {yellow, 0.5}, {blue, 1}}}
	Stops []GradientStop
}

LinearGradient blends colors along a line across a box, as CSS's linear-gradient does: two, From and To, or as many as its Stops.

e.LinearGradient(ui.LinearGradient{From: blue, To: yellow, Angle: 90, Oklab: true})

type ListRow

type ListRow struct {
	Context *Context
	Index   int
	// contains filtered or unexported fields
}

ListRow gives a row its shared context, index, selection and list focus.

func (ListRow) ListFocused

func (r ListRow) ListFocused() bool

func (ListRow) Selected

func (r ListRow) Selected() bool

type ListState

type ListState struct {
	// Handle names this list independently of its per-pass node.
	Handle

	// Key returns an identity for the item row i shows, such as its ID:
	// comparable, and unique among the rows. Without it, a row is its
	// index. With it, the state of a row (focus, text being edited, …)
	// follows its item, and the list keeps its place and its choice when
	// rows are added or removed above them, as when older messages load.
	Key func(row int) any
	// KeepOffset keeps a list with a Key where it is scrolled as its rows
	// move, rather than with the item at its top: for rows sorted again as
	// they change, as a process monitor's, which the list would otherwise
	// scroll along with the item at its top. The state of a row, the choice
	// and the row Shift chooses from still follow their items.
	KeepOffset bool
	// FollowEnd starts the list at its end, and keeps the end in view as
	// rows are added or grow while it shows it, as a chat or a log does:
	// scrolling away from the end stops following it, and scrolling back
	// to it follows again.
	FollowEnd bool
	// FollowAnimation, when set, makes a list following its end glide to
	// it as rows are added or grow, as the animation says (Smooth, a
	// spring, or a curve), rather than show it at once: what is added
	// comes up from below, as the chat apps scroll. A glide on its way
	// goes on from where it is as more comes, and the user scrolling stops
	// it. It shows the end at once where the desktop asks for less motion.
	FollowAnimation *Animation
	// Selected, when set, lets a click choose a row, as Up, Down, Home and
	// End do while the list has the keyboard focus, and Page Up and Page
	// Down on Linux and Windows: *Selected is the chosen row, -1 for none,
	// which shows in the accent color. The list's Changed reports a new
	// choice, and its Submitted a double click or Enter.
	Selected *int
	// Selection, when set, lets the user choose several rows, which it
	// holds by their keys: a click chooses one, Cmd-click (Ctrl-click on
	// Linux and Windows) adds a row or takes it out, and Shift-click
	// chooses those from the row last chosen to it, as Shift with the keys
	// that move the choice does; Cmd+A chooses all. On Linux and Windows,
	// Ctrl with those keys moves without choosing, and Ctrl+Space adds the
	// row there or takes it out. Selected, set as well, is the row last
	// chosen, where the keys move from. A right-click on a row not chosen
	// chooses it before its context menu opens, as Finder and Qt do, so
	// the menu acts on it.
	Selection Selector
	// MenuKeepsSelection leaves the rows chosen as they are when a
	// right-click opens a row's context menu: without it, a list with
	// Selection chooses the row clicked unless it is chosen, and in a Table
	// choosing cells the cell too, unless it is in the block. A list with
	// Selected alone never chooses on a right-click.
	MenuKeepsSelection bool
	// Label returns the text of row i: typing the first letters of a
	// row's text while the list has the keyboard focus chooses it, and
	// assistive technology reads it as the row's name.
	Label func(row int) string
	// Header, when set, reports whether row i heads a section: the header
	// of the section at the top of the list stays there while the rows of
	// its section scroll under it, until the next header pushes it away.
	// Give headers a background. Headers are not chosen.
	Header func(row int) bool
	// Reorder, when set, lets the user drag rows to another place in the
	// list: the rows chosen, when the row dragged is one, else that row,
	// which the list passes in order, and the row they go before, the
	// number of rows for the end. Move them there: the list shows where
	// they would go as they are dragged, and scrolls near its edges.
	Reorder func(rows []int, to int)
	// DragSelect, with Selection, chooses rows as the pointer drags over
	// them from the row it pressed: those from that row to the one under
	// the pointer, as a Shift-click on it would, and with Cmd (Ctrl on
	// Linux and Windows) held as the press began, those besides the rows
	// chosen. Held near the list's top or bottom, or past them, the drag
	// scrolls the list. A press on a row not chosen chooses it as the
	// pointer goes down, as a click would, and a press on a row chosen
	// waits for the release, so that a drag of the choice keeps it; this
	// is so in a Table choosing cells too. A list cannot both DragSelect
	// and Reorder.
	DragSelect bool
	// CellSelect, with Selection, makes a Table choose a block of cells:
	// the rows chosen, times the columns from Cells.Anchor to Cells.Cursor
	// in the order shown. A click on a cell chooses its row as a click on
	// the row does and its column; a Shift-click extends the rows and the
	// columns to it, and a Cmd-click adds its row or takes it out, keeping
	// the columns. Dragging over cells chooses those it goes over, as
	// DragSelect does the rows, scrolling sideways too. Left and Right
	// move Cells.Cursor, and Shift with them extends the columns, except in
	// an OutlineTable, where they open and close the rows as they do
	// without CellSelect; the keys that move the rows leave one column,
	// unless with Shift. The cells
	// of the block show as a chosen row does, as do the RowHeader cells of
	// whole rows chosen, and the one at Cells.Cursor in the row the keys
	// move from has a border while the table has the focus. A RowHeader
	// column chooses whole rows. A table cannot both CellSelect and
	// Reorder.
	CellSelect bool
	// Cells are the columns of the block CellSelect chooses.
	Cells ColumnRange
	// Sort, when set, is the column a Table's rows are sorted by: a click
	// on the header of a Sortable column sorts by it, ascending, and
	// another reverses the order, which the header shows. Sort the rows as
	// it says, when it changes. SortBy sorts by several columns, which
	// Sort, set with it, follows.
	Sort *SortOrder
	// SortBy sorts a Table's rows by several columns, the first first. A
	// click on a Sortable column's header sorts by it alone, as with Sort,
	// and reverses it when it was first; a Cmd-click (Ctrl-click on Linux
	// and Windows) or a Shift-click adds it after the others, ascending,
	// another makes it descending, and a third takes it out. The headers
	// show their direction and, when there are several, their place. It
	// gets a new slice as it changes, so one the app kept stays as it was.
	// When Sort is set too, the table keeps it the first of SortBy, the
	// zero SortOrder when SortBy is empty, for the app to read the column
	// that sorts first.
	SortBy *[]SortOrder
	// Columns keeps the order and the widths the user gave a Table's
	// columns, by ID: restore it from saved settings, and save it as it
	// changes.
	Columns TableLayout
	// RoundRows rounds the corners of a Table's chosen and hovered rows at
	// the theme's Radius, as a List's are, rather than leaving them square
	// from edge to edge.
	RoundRows bool
	// HeaderMenu, when set, gives a Table's header a context menu, built
	// as ContextMenu's is: col is the index of the column clicked in the
	// columns given to Table, not in the order the user moved them into,
	// or -1 for the part of the header past the columns, as AppKit's
	// clickedColumn. A menu built without items does not open.
	HeaderMenu func(m *Menu, col int)
	// CellMenu, when set, gives a Table's cells a context menu, built as
	// ContextMenu's is, over the whole cell with its padding: row and col
	// are as the cell builder receives them. A menu built without items
	// does not open. A context menu of what a cell holds takes the
	// right-click over it instead.
	CellMenu func(m *Menu, row, col int)
	// contains filtered or unexported fields
}

ListState is a List's place among its rows, how it behaves, and what it knows of the heights of its rows, kept in the app's state. Give each List a ListState of its own; set its fields before building the List.

func (*ListState) AtEnd

func (s *ListState) AtEnd() bool

AtEnd reports whether the list showed its end in the last frame, as Visible does its rows.

func (*ListState) CellSelected

func (s *ListState) CellSelected(row, col int) bool

CellSelected reports whether the cell of row and col, as a Table's cell builder receives them, is chosen: its row is chosen and, in a table choosing cells (CellSelect), its column is in the block, or it is a RowHeader cell of a row chosen with every column. In a table that does not choose cells, every cell of a chosen row is. It is false before the list is first built. A cell builder can style what it holds with it:

ui.Table(c, &app.grid, cols, len(app.rows), func(row, col int) {
	text := ui.Text(c, app.rows[row][col])
	if app.grid.CellSelected(row, col) {
		text.TextColor(c.Theme().AccentText)
	}
})

func (*ListState) DragSelecting

func (s *ListState) DragSelecting() bool

DragSelecting reports whether a drag choosing rows (DragSelect), or the cells of a Table (CellSelect), goes on: the pointer holds it. An app can put off work that follows the choice, as a sum of the cells chosen, until it ends: from the frame of the release on, it reports false.

func (*ListState) ExtendTo

func (s *ListState) ExtendTo(row int)

ExtendTo chooses the rows from the one Shift extends from to row, as a Shift-click on it does, and makes row the one the keys move from: for an app's own keys, as a key that extends the choice to the last row. Call it in the view, after the list is built. It does nothing without Selection.

func (*ListState) Focus

func (_handle *ListState) Focus(c *Context) bool

Focus gives the list the keyboard focus and reports whether it was built in the current pass of c. A pending focus request can wait until a hidden list returns:

if app.focusFiles && app.files.Focus(c) {
	app.focusFiles = false
}

Call it after building the list, or while building its rows.

func (*ListState) FocusWithin

func (_handle *ListState) FocusWithin(c *Context) bool

FocusWithin reports whether the list or one of its descendants has the keyboard focus, with the same lifetime as Focused. Row builders can use it before List returns, without saving an Element from an earlier frame.

func (*ListState) Focused

func (_handle *ListState) Focused(c *Context) bool

Focused reports whether the List, Table or Outline using s has the keyboard focus. Call it from the view, after building the list or while building its rows. It returns false when s was not built in the current pass of c, including when the list is hidden.

func (*ListState) ScrollIntoView

func (s *ListState) ScrollIntoView(row int)

ScrollIntoView scrolls the list as little as shows row whole, as Element.ScrollIntoView does an element.

func (*ListState) ScrollTo

func (s *ListState) ScrollTo(row int, align Align)

ScrollTo scrolls the list to show row at align: Start shows it at the top, Center in the middle and End at the bottom. Call it from the view: the list scrolls as the frame is laid out, to where the row is once it is measured.

func (*ListState) ScrollToEnd

func (s *ListState) ScrollToEnd()

ScrollToEnd scrolls the list to its end, where FollowEnd follows it again.

func (*ListState) SelectColumns

func (s *ListState) SelectColumns(from, to string)

SelectColumns chooses every row of a Table choosing cells (CellSelect) and the columns from the one whose ID is from to the one whose ID is to, which becomes Cells.Cursor. Call it in the view, after the table is built.

func (*ListState) SelectedColumns

func (s *ListState) SelectedColumns() []string

SelectedColumns returns the IDs of the columns of the block of cells a Table chooses (CellSelect), in the order shown in the last frame, without RowHeader columns.

func (*ListState) Shortcut

func (_handle *ListState) Shortcut(c *Context, mods Modifiers, key Key) bool

Shortcut reports whether mods+key was pressed while the list or one of its descendants had the focus, as Element.Shortcut does. Call it after building the list, or while building its rows. A list not built in the current pass of c registers and handles no shortcuts.

func (*ListState) Visible

func (s *ListState) Visible() (first, last int)

Visible returns the first and the last row the list showed in the last frame, last below first when it showed none: a list nearing the end of what was loaded, say, loads more. A frame that changes them builds another, for what read them.

type Material

type Material interface {
	// PaintMaterial paints the material over box, rounded by radii, in
	// DIPs, under the element's border and children.
	PaintMaterial(p *Painter, box Rect, radii [4]float32)
}

Material is what Element.Material fills an element with in place of a background: a look a package paints, as the glass plugin's Liquid Glass (github.com/HyperparameterSI/golet/backend/plugins/glass).

type MaterialBuilder

type MaterialBuilder interface {
	Material
	BuildMaterial(Element) Material
}

MaterialBuilder builds a material using a checked element.

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

Menu is a menu being built, by the function given to ContextMenu or Element.Menu. Its items show in the order they are added.

func (m *Menu) EditItems()

EditItems adds the editing items of the text the menu opened on, as its menu has them without ContextMenu: Copy and Select All for selectable text, the platform's text field items for a text input. Choosing one does its command on the text, without reaching the menu's function. It adds nothing to a menu that opened on no text.

func (m *Menu) Item(label string) *MenuItem

Item adds an item showing label.

func (m *Menu) Separator()

Separator adds a line between groups of items.

func (m *Menu) Submenu(label string, build func(m *Menu)) *MenuItem

Submenu adds an item showing label that opens a submenu, which build fills as ContextMenu's function fills the menu.

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

MenuItem is an item of a Menu. Its methods set it up and return it, for chaining, and Chosen reports the choice.

func (it *MenuItem) Checked(on bool) *MenuItem

Checked shows a check mark by the item when on is true, as for a setting that choosing the item toggles.

func (it *MenuItem) Chosen() bool

Chosen reports whether the item was chosen, in the frame after the user chose it.

func (it *MenuItem) Disabled(d bool) *MenuItem

Disabled shows the item grayed out when d is true: it cannot be chosen.

func (it *MenuItem) Shortcut(mods Modifiers, key Key) *MenuItem

Shortcut shows a key with modifiers by the item, as the shortcut that does the same; the view handles the key itself, as with Context.Shortcut.

type MeterLevels

type MeterLevels struct {
	Warning, Critical float64
}

MeterLevels are the levels of a Meter from which its value shows it is worse: the theme's Warning color from Warning, its Danger color from Critical. A Critical below Warning makes low values the bad ones, as a battery's. Their zero value shows the theme's Success color throughout.

type Modifiers

type Modifiers uint8

Modifiers are modifier keys.

type Motion

type Motion struct {
	// X and Y move it by as many DIPs.
	X, Y float32
	// Opacity is how opaque it is there: 0, as by default, is
	// transparent, and 1 opaque.
	Opacity float32
	// Collapse makes it nothing along its parent's direction: no height in
	// a column, no width in a row. Its content keeps its layout, clipped.
	Collapse bool
	// Scale is how large it is there, around its TransformOrigin: 0.9 a
	// tenth smaller; 0, as by default, keeps it at its size, as 1 does.
	// Rotate turns it by as many degrees clockwise.
	Scale, Rotate float32
}

Motion is where an element appearing comes from, or where one going goes, from its place in the layout.

type NativeWebView

type NativeWebView = surface.WebView

NativeWebView is a web view a window made for its content to show, as *golet.WebView, of golet.Window.NewWebView.

type Orientation

type Orientation uint8

Orientation says which arrows move the focus in a FocusGroup: Left and Right (Horizontal), Up and Down (Vertical), or all four (Horizontal|Vertical).

const (
	Horizontal Orientation = 1 << iota
	Vertical
)

type OutlineState

type OutlineState[K comparable] struct {
	// List is the state of the rows: their place, and how they are chosen,
	// as a List's. Its Key is the rows' items; a Selection takes them, of
	// type K.
	List ListState
	// Open holds the items showing their children.
	Open Selection[K]
	// Indent is the width in DIPs each level adds before a row's arrow,
	// the theme's Space(4) when zero. It must not be negative.
	Indent float32
	// contains filtered or unexported fields
}

OutlineState is the state of an Outline or an OutlineTable: its rows, as a List's, and the items that are open, showing their children. The rows' keys are the items, of type K, so that their place, choice and state follow them as items open and close above them.

type app struct {
	files ui.OutlineState[string] // paths
	file  int
}

app.files.List.Selected = &app.file

func (*OutlineState[K]) Depth

func (s *OutlineState[K]) Depth(row int) int

Depth returns how deep the item of row i is: 0 for the items at the top.

func (*OutlineState[K]) Item

func (s *OutlineState[K]) Item(row int) K

Item returns the item row i shows, in the last frame.

func (*OutlineState[K]) Rows

func (s *OutlineState[K]) Rows() int

Rows returns how many rows the outline shows: its items at the top, and the children of those open, in the last frame.

type Painter

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

Painter draws an element's own content in Element.Draw and DrawOver callbacks, in DIPs relative to the window.

func (*Painter) Accelerated

func (p *Painter) Accelerated() bool

Accelerated reports whether the frame draws on a GPU: false where it draws in memory (with GOLET_GPU=0, without a GPU Golet can draw with, as in most virtual machines, and in Render and tests) and where the GPU's renderer draws on the CPU (Direct3D's WARP, Mesa's llvmpipe, browsers' SwiftShader). A drawing that costs too much there, as a shader covering much of the window (package shader runs one pixel by pixel on the CPU), can draw less, or nothing. Should the answer change, as when the GPU goes away or comes back, the window is painted again.

func (*Painter) After

func (p *Painter) After(d time.Duration)

After asks for the element to be painted again after d, for a drawing that changes then, as a spinner's next step: unless something else changed meanwhile, that frame paints the elements of this one again without building the view. An element out of view is not painted, so it asks for none.

func (*Painter) AnimationFrame

func (p *Painter) AnimationFrame()

AnimationFrame asks for the element to be painted again as soon as the display can show it, for a drawing that moves with Now while the layout stays, as a spinner's: unless something else changed meanwhile, the next frame paints the elements of this one again without building the view. Call it in every frame while the drawing moves; an element out of view is not painted, so it asks for none.

func (*Painter) Clip

func (p *Painter) Clip(r Rect, radius float32, fn func())

Clip restricts what fn draws to r.

func (*Painter) Effect

func (p *Painter) Effect(fx *scene.Effect, r Rect, radii [4]float32, blur float32, params [5][4]float32)

Effect paints the rectangle r rounded by radii, in DIPs, with an effect: shaders the renderers draw it with (see scene.Effect), which only this module's packages define, as the official plugins do. params are the effect's own, in device pixels (Scale), and blur the standard deviation of the blur of its backdrop, in device pixels, for an effect reading one.

func (*Painter) EffectBackdrop

func (p *Painter) EffectBackdrop(r Rect, blur float32, inset Point) EffectBackdrop

EffectBackdrop returns where the backdrop of an effect over r, in DIPs, blurred by blur pixels, lies, its points from inset, in pixels from the corner of r on the pixel grid: what the renderers read for it, the same for every renderer.

func (*Painter) EffectColor

func (p *Painter) EffectColor(c Color) (srgb, wide [4]float32)

EffectColor returns c as a parameter of an effect: straight RGBA from 0 to 1, its sRGB value, and wide, its color outside the sRGB gamut in extended sRGB, which the effect's Metal shader takes where e.wide tells that the target keeps it (wide is the sRGB value for a color inside the gamut). Like a color an element paints, it has the frame drawn in a wide gamut where the window shows one.

func (*Painter) EffectWords

func (p *Painter) EffectWords(n int) []uint32

EffectWords returns n words, zero, for the uniforms of an effect this frame paints (ShaderInput), which last until the frame is drawn.

func (*Painter) Fill

func (p *Painter) Fill(r Rect, c Color, radius float32)

Fill paints a rounded rectangle.

func (*Painter) FillConicGradient

func (p *Painter) FillConicGradient(r Rect, g ConicGradient, radius float32)

FillConicGradient fills a rounded rectangle with a conic gradient around it.

func (*Painter) FillGradient

func (p *Painter) FillGradient(r Rect, g LinearGradient, radius float32)

FillGradient paints a rounded rectangle with a gradient.

func (*Painter) FillPath

func (p *Painter) FillPath(path *Path, c Color)

FillPath fills a path (non-zero winding).

func (*Painter) FillPathConicGradient

func (p *Painter) FillPathConicGradient(path *Path, g ConicGradient)

FillPathConicGradient fills a path with a conic gradient around its bounds.

func (*Painter) FillPathGradient

func (p *Painter) FillPathGradient(path *Path, g LinearGradient)

FillPathGradient fills a path with a gradient across its bounds, as the area under a chart's line.

func (*Painter) FocusRing

func (p *Painter) FocusRing(r Rect, radius [4]float32)

FocusRing draws the ring that shows the keyboard focus around r.

func (*Painter) Glyphs

func (p *Painter) Glyphs(glyphs []Glyph, x, y float32, c Color)

Glyphs draws glyphs that Shape made, from x, on the baseline at y, in color c.

func (*Painter) Icon

func (p *Painter) Icon(s *SVG, r Rect, c Color)

Icon draws the shapes of an SVG fitted in r, in color c.

func (*Painter) Image

func (p *Painter) Image(src ImageSource, r Rect, fit Fit)

Image draws a bitmap, or an SVG in its own colors (with the theme's text color for its currentColor), scaled to fit r.

func (*Painter) ImageRegion

func (p *Painter) ImageRegion(b *Bitmap, src, dst Rect, o ImageOptions)

ImageRegion draws the part src of bitmap b, in its pixels (empty for all of it), stretched into dst, as Image draws a bitmap (pixelated if it is), unless dst is outside what the painter shows. Nothing of the bitmap around src shows, so that the parts of a bitmap holding many, as the icons of a sheet or the frames of an animation, draw on their own. Under a transform (Painter.Transform), dst is where it is, not snapped to pixels, so that a part moving through a zoomed view glides:

p.ImageRegion(icons, ui.Rect{X: 32, W: 16, H: 16}, box, ui.ImageOptions{})

func (*Painter) Line

func (p *Painter) Line(x0, y0, x1, y1, width float32, c Color)

Line paints a straight horizontal or vertical line between two points, width DIPs thick.

func (*Painter) MeasureText

func (p *Painter) MeasureText(width float32, spans ...Span) (w, h float32)

MeasureText returns the size spans of text take as Painter.RichText draws them, wrapping lines at width DIPs (none for 0).

func (*Painter) Now

func (p *Painter) Now() time.Time

Now returns the time of the frame being painted, which drawings that move compute from.

func (*Painter) RichText

func (p *Painter) RichText(x, y, width float32, spans ...Span) (w, h float32)

RichText draws spans of text as RichText shows them, with its top-left corner at (x, y), wrapping lines at width DIPs (none for 0), and returns the size it takes. What the spans leave zero takes the theme's font, FontSize and Text color:

w, _ := p.MeasureText(0, label)
p.RichText(r.X+(r.W-w)/2, r.Y, 0, label)

func (*Painter) Scale

func (p *Painter) Scale() float32

Scale returns how many device pixels a DIP is, for drawing that lines up with the pixels of the display.

func (*Painter) ShaderEffect

func (p *Painter) ShaderEffect(fx *scene.Effect, r Rect, radius float32, in ShaderInput)

ShaderEffect paints the rectangle r rounded by radius, in DIPs, with fx, the effect of a shader of package ui/shader (scene.Effect.Shader), reading in. Only this module's packages make such effects.

func (*Painter) ShaderFill

func (p *Painter) ShaderFill(fx *scene.Effect, box Rect, in ShaderInput, fn func())

ShaderFill paints the text, paths and icons that fn paints with fx, the effect of a shader of package ui/shader, in place of their colors: each pixel the shader's color times the shape's coverage. box, in DIPs, is the box the shader fills, whose top left corner its positions start from. Glyphs of color, as emoji, keep their colors, and what fn paints besides, as rectangles and images, paints as it would. fx reads in. Only this module's packages make such effects.

func (*Painter) Shadow

func (p *Painter) Shadow(r Rect, radius, x, y, blur, spread float32, c Color)

Shadow paints the box shadow of a rounded rectangle as Element.Shadow does: offset by x and y, blurred by blur and grown by spread DIPs, and only outside the rectangle, so that it does not show through what is drawn there.

func (*Painter) Stroke

func (p *Painter) Stroke(r Rect, c Color, radius, width float32)

Stroke paints the outline of a rounded rectangle, width DIPs wide inside its edge.

func (*Painter) StrokeDashed

func (p *Painter) StrokeDashed(r Rect, c Color, radius, width float32)

StrokeDashed paints the outline of a rounded rectangle in dashes, as a dashed border.

func (*Painter) StrokePath

func (p *Painter) StrokePath(path *Path, width float32, c Color)

StrokePath draws the outline of a path, width DIPs wide, with round joins and caps.

func (*Painter) StrokePathConicGradient

func (p *Painter) StrokePathConicGradient(path *Path, width float32, g ConicGradient)

StrokePathConicGradient draws the outline of a path as StrokePath does, in a conic gradient around its bounds.

func (*Painter) StrokePathGradient

func (p *Painter) StrokePathGradient(path *Path, width float32, g LinearGradient)

StrokePathGradient draws the outline of a path as StrokePath does, in a gradient across its bounds.

func (*Painter) StrokePolyline

func (p *Painter) StrokePolyline(points [][2]float32, width float32, c Color)

StrokePolyline draws a line through points in DIPs, width DIPs wide, with round joins and caps, as StrokePath draws a path of straight lines: a NaN or infinite point breaks the line there, and a point alone draws nothing. It suits lines that change every frame, as live charts: on a GPU, an opaque line draws each segment as a rounded rectangle instead of rasterizing a mask of the whole line, so that its edges can look a little bolder where segments overlap. Translucent lines draw as StrokePath's, which keeps overlaps from showing darker.

func (*Painter) Text

func (p *Painter) Text(x, y float32, s string, size float32, c Color)

Text draws a line of text with its top-left corner at (x, y).

func (*Painter) TextLayout

func (p *Painter) TextLayout(layout *TextLayout, x, y float32, color Color)

TextLayout paints a retained layout at (x,y) in DIPs, with color as the default foreground. Span colors and decorations paint as RichText does.

func (*Painter) TextLine

func (p *Painter) TextLine(l *text.Layout, x, y float32, color func(cluster int) Color)

TextLine paints the glyphs of the first line of l, a layout of this module's text system that only its packages make, as package ui/editor does, from x, on the baseline at y, each in the color color returns for the rune its cluster starts at. Glyphs outside the painter's clip are left out.

func (*Painter) Theme

func (p *Painter) Theme() *Theme

Theme returns the theme of the view being painted.

func (*Painter) Transform

func (p *Painter) Transform(t Transform, ox, oy float32, fn func())

Transform transforms what fn draws by t around the point (ox, oy), which t leaves where it is, after the painter's own transforms: it nests. A view that pans and zooms, as a map or a diagram, draws its content through one, and a dial turns its needle around its center with another:

view := ui.Translation(-panX, -panY).Then(ui.Scaling(zoom, zoom))
p.Transform(view, r.X, r.Y, func() {
	drawDiagram(p)
	p.Transform(ui.Rotation(angle), cx, cy, func() { p.Line(cx, cy, cx, cy-40, 2, red) })
})

Clips made in fn turn with what it draws, and what the transform moves out of view is culled as usual. Input is not transformed: the pointer comes in the element's coordinates, which the app maps to its content itself.

func (*Painter) Visible

func (p *Painter) Visible() Rect

Visible returns what the painter's clip leaves of the window, in DIPs: the part of an element's box that shows inside the scroll containers and clips around it, as an element taller than the window, showing a long document, paints only what falls in it. It is in the coordinates the painter draws in: under a transform, an element's or the painter's, the clip taken back through it, so an element scaled up sees as much less of itself as shows.

type Path

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

Path is a vector shape, in DIPs, for Painter.FillPath and StrokePath: icons, check marks, charts.

func (*Path) Bounds

func (p *Path) Bounds() Rect

Bounds returns the smallest box holding the path's points and the control points of its curves, in DIPs: the box of a circle (Circle), of lines, and of curves whose control points lie on it; others may fit in less. Empty paths have an empty box.

func (*Path) Circle

func (p *Path) Circle(cx, cy, r float32) *Path

Circle adds a circle as a subpath.

func (*Path) Close

func (p *Path) Close() *Path

Close closes the subpath.

func (*Path) CubeTo

func (p *Path) CubeTo(c1x, c1y, c2x, c2y, x, y float32) *Path

CubeTo draws a cubic Bézier curve to (x, y) with control points (c1x, c1y) and (c2x, c2y).

func (*Path) LineTo

func (p *Path) LineTo(x, y float32) *Path

LineTo draws a line to (x, y).

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float32) *Path

MoveTo starts a new subpath at (x, y).

func (*Path) QuadTo

func (p *Path) QuadTo(cx, cy, x, y float32) *Path

QuadTo draws a quadratic Bézier curve to (x, y) with control point (cx, cy).

func (*Path) Reset

func (p *Path) Reset() *Path

Reset empties the path and removes Trim, retaining its command storage.

func (*Path) Trim

func (p *Path) Trim(from, to float32) *Path

Trim keeps of the path, as a Painter fills or strokes it, the part of its length from from to to, as fractions of it, its subpaths one after another, and returns the path: 0 to 0.5 draws its first half, and a check mark draws itself as to animates from 0 to 1, as SwiftUI's trim(from:to:) and Motion's pathLength. Trimmed, closed subpaths draw open, and a stroke trimmed shorter than its width fades with its length, rather than its round caps showing a dot that comes or goes at once.

type Placement

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

A Placement says where along the timeline a tween or a label starts: relative to the tween before it, at a label, or at a time, as GSAP's position parameter. With no placement, what comes next follows the tween before it at once, as AfterPrevious(0). Nothing starts before the timeline does: a placement before its start is at its start.

tl.Tween(ui.Tween{...}, ui.AfterPrevious(-150*time.Millisecond)) // overlaps it by 150ms
tl.Tween(ui.Tween{...}, ui.WithPrevious(100*time.Millisecond))
tl.Tween(ui.Tween{...}, ui.AtLabel("intro", 200*time.Millisecond))
tl.Tween(ui.Tween{...}, ui.AtTime(500*time.Millisecond))

func AfterPrevious

func AfterPrevious(offset time.Duration) Placement

AfterPrevious starts a tween offset after the tween before it ends, or with a negative offset that long before, to overlap it, as GSAP's "+=" and "-=".

func AtLabel

func AtLabel(name string, offset time.Duration) Placement

AtLabel starts a tween offset after a Label of the timeline, as rows staggered from one label each start i times a step after it:

for i := range rows {
	rows[i] = tl.Tween(ui.Tween{From: 0, To: 1, Duration: 200 * time.Millisecond},
		ui.AtLabel("rows", time.Duration(i)*40*time.Millisecond))
}

func AtTime

func AtTime(t time.Duration) Placement

AtTime starts a tween at time t of the timeline.

func WithPrevious

func WithPrevious(offset time.Duration) Placement

WithPrevious starts a tween offset after the tween before it starts, to move something along with it, as GSAP's "<".

type Point

type Point struct{ X, Y float32 }

Point is a position in DIPs relative to an element or text layout.

type Pose

type Pose struct {
	X, Y, Scale, Rotate, Fade float32
}

Pose is where an element shows, from its place in the layout, which AnimatePose moves it to: moved by X and Y DIPs, scaled by Scale around its TransformOrigin (0 keeps its size, as 1 does), turned by Rotate degrees clockwise, and faded by Fade, from 0, opaque, to 1, gone.

type Preferences

type Preferences struct {
	// Accent is the accent color the user chose, which the default theme
	// takes; A is 0 where the desktop has none.
	Accent Color
	// ReduceMotion asks for less motion: macOS's Reduce Motion, Windows's
	// animation effects and GNOME's animations turned off. Animate then
	// goes to its target at once; Loop, which shows that something is
	// going on, goes on.
	ReduceMotion bool
	// HighContrast asks for more contrast: macOS's Increase Contrast,
	// Windows's contrast themes, the desktop portal's higher contrast. The
	// default theme then draws borders and secondary text darker (lighter
	// in the dark), and the focus ring opaque.
	HighContrast bool
	// TextScale is how many times larger than usual text should be, as
	// Windows's and GNOME's text size settings say, 1 for usual: the
	// default theme's FontSize is that much larger.
	TextScale float32
}

Preferences are settings of the desktop that the system's own controls follow. The default theme follows them, and Animate follows ReduceMotion; a theme of your own (Context.SetTheme) and drawing of your own may read them with Context.Preferences.

type Rect

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

Rect is a rectangle in DIPs.

func (Rect) Contains

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

Contains reports whether the point is inside r.

type Ref

type Ref = Handle

Ref is an alias for Handle. Bind and Handle are preferred for new code.

type Role

type Role uint8

Role is what an element is to assistive technology. Widgets set their own; other elements get one from what they do: one that is clickable and takes the focus is a button, a text is a text, a scroll container a scroll area, and one with a Label, or that takes the focus, a group.

const (
	// RoleAuto finds the role from what the element does.
	RoleAuto Role = iota
	// RoleNone leaves the element out, but not its children.
	RoleNone
	RoleGroup
	RoleText
	RoleButton
	RoleLink
	RoleCheckBox
	RoleRadio
	RoleSwitch
	RoleSlider
	RoleProgress
	RoleTextField
	RoleImage
	RoleList
	RoleScroll
	RoleDialog
	RolePopup
	RoleTooltip
	RolePopUpButton
	RoleTabList
	RoleTab
	RoleSplitter
	RoleStatus
	RoleTable
	RoleRow
	RoleCell
	RoleColumnHeader
	RoleTree
	RoleTreeItem
	// RoleListItem is an item of a list: the rows of a List are.
	RoleListItem
	// RoleMenuButton is a button opening a menu (Element.Menu).
	RoleMenuButton
	// RoleToolbar holds controls (Toolbar), RoleRadioGroup radio buttons
	// (RadioGroup, Segmented), and RoleToggleButton is a button that stays
	// pressed (Toggle).
	RoleToolbar
	RoleRadioGroup
	RoleToggleButton
	// RoleComboBox is a text input with a popup of options (ComboboxBase).
	RoleComboBox
	// RoleDisclosure is a button showing or hiding content below it, as
	// the trigger of a collapsible (CollapsibleBase), expanded while open.
	RoleDisclosure
	// RoleMeter shows a value in a range (Meter), and RoleStepper steps a
	// value in one (Stepper).
	RoleMeter
	RoleStepper
	// RoleColorWell is a button showing a color, which it opens a picker
	// of (ColorWell).
	RoleColorWell
	// RoleAlertDialog is a dialog asking about something important
	// (AlertDialog).
	RoleAlertDialog
	// RoleMenu holds the items of a menu drawn in the window, as a drop-down
	// menu's panel, and RoleMenuBar the titles of menus along it.
	// RoleMenuItem is an item of either, and RoleMenuItemCheckBox and
	// RoleMenuItemRadio items showing a choice, checked with Checked.
	RoleMenu
	RoleMenuBar
	RoleMenuItem
	RoleMenuItemCheckBox
	RoleMenuItemRadio
	// RoleHeading is the title of a section, named by its text, its rank
	// set with Level.
	RoleHeading
)

type Route

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

Route is a page a Router's View builds: Match tells its path apart and Param reads the parts of the path the pattern matched.

func (*Route) Match

func (r *Route) Match(pattern string) bool

Match reports whether the page's path matches pattern, whose parts between slashes are either the same as the path's or wildcards: {name} takes any one part, and {name...}, at the end, the rest of the path, which may be empty. Param returns what they took. A slash at the end of the path or the pattern makes no difference.

case r.Match("/notes/{id}"):        // "/notes/42"
case r.Match("/files/{path...}"):   // "/files", "/files/docs/a.txt"

func (*Route) Page

func (_handle *Route) Page() Element

Page returns the element holding the page, a column filling the router, for its style.

func (*Route) Param

func (r *Route) Param(name string) string

Param returns what the wildcard name of the pattern Match last matched took, unescaped, or of a layout's around, "" if none has it.

func (*Route) Path

func (r *Route) Path() string

Path returns the path of the page, as "/notes/42"; in a Route.View, the part of the path its layout leaves, as "/fonts" of "/settings/fonts".

func (*Route) Query

func (r *Route) Query(name string) string

Query returns the value of the query parameter name, "" if the page has none.

func (*Route) Title

func (r *Route) Title(title string)

Title names the page: screen readers read it as the page shows, and BackButton and ForwardButton list it. Inside a layout, the title of the page inside names the entry of the history.

func (*Route) View

func (_handle *Route) View(c *Context, fn func(r *Route)) Element

View builds the pages of the rest of the path, which the {name...} wildcard of the pattern Match matched last took, with fn, in a column taking the room it is given, and returns the column: the page holding it is a layout, as a page of settings with a list of its sections around the section shown. The layout stays as the pages inside change, keeping its state, and they slide or fade in its place, keep their state in the history and take the focus as the router's pages do. Their patterns match the rest of the path, and Param returns the wildcards of the layout's pattern too:

case r.Match("/settings/{section...}"):
	app.settingsSidebar(c)
	r.View(c, func(r *ui.Route) {
		switch {
		case r.Match("/general"):
			app.general(c)
		case r.Match("/fonts"):
			app.fonts(c)
		}
	})

View panics when the pattern Match matched last has no {name...}.

type Router

type Router struct {
	Handle

	// Transition is how pages replace each other, and Animation, if set,
	// how they move then: as a spring (Snappy, …) or a curve, rather than
	// easing out over 250 ms as they slide, 150 ms as they fade.
	Transition Transition
	Animation  *Animation
	// contains filtered or unexported fields
}

Router keeps the history of the pages of a window, or of a part of one, as a browser does for a tab: the page shown, those before it that Back returns to, and those after it that Forward goes to again. A page is a path, as "/notes/42?tab=info", and View builds the one shown. Make a router once, in a field of the app's state, and build its pages in the view:

type notesApp struct{ router *ui.Router }

app := &notesApp{router: ui.NewRouter("/notes")}

func (app *notesApp) view(c *ui.Context) {
	app.router.View(c, func(r *ui.Route) {
		switch {
		case r.Match("/notes"):
			r.Title("Notes")
			app.notes(c)
		case r.Match("/notes/{id}"):
			r.Title("Note")
			app.note(c, r.Param("id"))
		default:
			ui.Text(c, "Not found")
		}
	})
}

Push goes to a page and Back comes back, as do Cmd+[ and Cmd+] on macOS, Alt+Left and Alt+Right elsewhere, the back and forward buttons of a mouse, BackButton and ForwardButton, and Links to paths in its pages.

A page can be a layout around the pages of the rest of the path, which Route.View builds: the layout stays, keeping its state, as they change inside it.

A page keeps the state of its elements while it is in the history: going back to one finds it scrolled where it was, with what was typed, and the keyboard focus where it was. Going to a page moves the focus into it, unless the focus is outside the page that changes, as in a sidebar choosing the pages, where it stays: screen readers then hear the title of the page. Pages slide or fade in (Transition).

In a browser, the first router a window shows follows the history of the browser's tab, in the URL's fragment, as "#/notes/42": going to a page adds an entry to it, the browser's back and forward buttons go through the router's pages, and a URL with a fragment opens the app at its page.

The zero Router shows "/". As the rest of the app's state, it is read and changed on the main thread: from another goroutine, change it in Window.Update.

func NewRouter

func NewRouter(path string) *Router

NewRouter returns a router showing the page at path.

func (*Router) Back

func (r *Router) Back()

Back shows the page before, if any.

func (*Router) CanGoBack

func (r *Router) CanGoBack() bool

CanGoBack reports whether there is a page to go back to, and CanGoForward one to go forward to.

func (*Router) CanGoForward

func (r *Router) CanGoForward() bool

func (*Router) Forward

func (r *Router) Forward()

Forward shows the page after, which Back left, if any.

func (*Router) Go

func (r *Router) Go(n int)

Go moves n pages through the history: back for a negative n, forward for a positive one, as far as it goes.

func (*Router) Location

func (r *Router) Location() string

Location returns the path and the query of the page shown, as "/notes/42?tab=info", which Push and Replace take, to show the page again when the app starts.

func (*Router) Path

func (r *Router) Path() string

Path returns the path of the page shown, as "/notes/42", without its query.

func (*Router) Push

func (r *Router) Push(target string)

Push goes to the page at target, after the page shown, whose later pages it forgets: an absolute path, as "/notes/42", or one relative to the page shown, as a link in a web page, as "?tab=info" or "../". Going to the page shown does nothing. The same path with another query is the same page, keeping its state, in another entry of the history, and layouts whose part of the path stays stay too.

func (*Router) Query

func (r *Router) Query(name string) string

Query returns the value of the query parameter name of the page shown, "" if it has none.

func (*Router) Replace

func (r *Router) Replace(target string)

Replace shows the page at target in place of the page shown, in its entry of the history, as after a page moved: Back does not return to the page replaced. The same path with another query is the same page, keeping its state, as a search page following what is typed.

func (*Router) Title

func (r *Router) Title() string

Title returns the title of the page shown, as its Route set it in the last frame.

func (*Router) View

func (_handle *Router) View(c *Context, fn func(r *Route)) Element

View builds the page shown with fn, in a column taking the room it is given, and returns the column. As a page slides in, it builds the one going away too, which takes neither the pointer nor the keyboard.

type SVG

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

SVG is a vector image: an icon, a logo, an illustration. It stays sharp at any size. Parse it once, not in the view, and show it with Icon, in the color of the text, or with Image, in its own colors:

//go:embed icons/save.svg
var saveSVG []byte

var save = ui.MustParseSVG(saveSVG)

ui.Icon(c, save)

Golet draws the paths and basic shapes of SVG, with groups, use and symbol elements, transforms, colors, gradients, strokes and their dashes, opacity, clip paths, masks and style sheets of simple selectors. It leaves out text, embedded images, patterns, markers and filters: convert text to paths before.

func MustParseSVG

func MustParseSVG(data []byte) *SVG

MustParseSVG is ParseSVG for SVGs that are part of the program, such as embedded files: it panics when one is in error.

func ParseSVG

func ParseSVG(data []byte) (*SVG, error)

ParseSVG parses an SVG document.

func (*SVG) Size

func (s *SVG) Size() (w, h float32)

Size returns the size the SVG says it has, its width and height or those of its viewBox, which Image shows as DIPs.

type ScrollState

type ScrollState struct {
	Handle

	// X and Y are how far the content is scrolled left and up, in DIPs:
	// right to left (Direction), X is how far it is scrolled right, from
	// its start at the right. Set them to scroll: the container keeps them
	// within its content, so that 0 shows the start and math.MaxFloat32
	// the end.
	X, Y float32
	// MaxX and MaxY are as far as X and Y go, as the frame laid the content
	// out: Y is MaxY at the end. The container sets them.
	MaxX, MaxY float32
	// contains filtered or unexported fields
}

ScrollState is how far a scroll container scrolls its content, kept in the app's state with TrackScroll.

func (*ScrollState) ScrollTo

func (s *ScrollState) ScrollTo(x, y float32, a Animation)

ScrollTo scrolls the container smoothly to x and y as a says, from where it shows its content, as SwiftUI's scrollTo in withAnimation: math.MaxFloat32 is the end. Called again on the way, it turns smoothly toward the new place; the user scrolling stops it. While the desktop asks for less motion, or the frame disables animations, it scrolls at once.

if ui.Button(c, "Back to top").Clicked() {
	app.feed.ScrollTo(0, 0, ui.Smooth)
}

func (*ScrollState) Scrolling

func (s *ScrollState) Scrolling() bool

Scrolling reports whether a ScrollTo is on its way.

type SegmentedParts

type SegmentedParts struct {
	Track Element
	// contains filtered or unexported fields
}

SegmentedParts contains checked handles for the parts of a custom widget.

func SegmentedBase

func SegmentedBase(c *Context, selected *int, n int) SegmentedParts

SegmentedBase creates a segmented control of n segments without a look, of which *selected is the index of the one chosen: a radio group (see RadioGroup) whose radio buttons are the segments, built in Track with Segment. Track's Changed reports a new choice. Segmented is SegmentedBase with the theme's look.

func (SegmentedParts) Segment

func (_handle SegmentedParts) Segment(i int) Element

Segment creates segment i: a radio button choosing i. Style it from whether i is the one chosen, and give it children.

type SelectParts

type SelectParts[T comparable] struct {
	Trigger Element
	// contains filtered or unexported fields
}

SelectParts contains checked handles for the parts of a custom widget.

func SelectBase

func SelectBase[T comparable](c *Context, selected *T) SelectParts[T]

SelectBase creates a select without a look: a trigger that opens a popup of options, which choose *selected. With the focus on the trigger, the arrows open the popup and move among its options, Enter and Space choose one, and Escape closes it; the trigger's Changed reports a new choice. Give the trigger children showing the choice, and build the options in Popup with Item:

sel := ui.SelectBase(c, &app.size)
sel.Trigger.Padding(6, 10).Border(1, gray).Children(func() {
	ui.Text(c, app.size)
})
sel.Popup(func(panel ui.Element) {
	panel.Padding(4).Background(white).Border(1, gray)
	for _, size := range sizes {
		item := sel.Item(size).Padding(6, 10)
		if item.Highlighted() {
			item.Background(blue).TextColor(white)
		}
		item.Children(func() { ui.Text(c, size) })
	}
})

Select is SelectBase with the theme's look.

func (SelectParts[T]) Highlight

func (_handle SelectParts[T]) Highlight(value T)

Highlight moves the highlight to the option of value while the popup shows, as a select of your own may do as the user types the option's first letters; Enter then chooses it.

func (SelectParts[T]) Item

func (_handle SelectParts[T]) Item(value T) Element

Item creates an option choosing value: a row that is Highlighted when the pointer or the arrows are on it, and chooses value and closes the popup when clicked. The option the highlight moves to scrolls into view, once, so that the wheel scrolls on past it.

func (SelectParts[T]) Open

func (_handle SelectParts[T]) Open() bool

Open reports whether the popup shows.

func (SelectParts[T]) Popup

func (_handle SelectParts[T]) Popup(fn func(panel Element)) Element

Popup shows the popup below the trigger, at least as wide, while it is open: fn styles the panel and builds the options in it with Item. Clicking outside it or pressing Escape closes it. It returns the panel, or nil when the popup is closed.

type SelectedText

type SelectedText struct {
	// ID is the paragraph's element's (Element.ID).
	ID uint64
	// Text is the paragraph's text, and Start and End the runes of it the
	// selection holds.
	Text       string
	Start, End int
}

SelectedText is the part of a paragraph that the selection of a Selectable container holds.

type Selection

type Selection[K comparable] struct {
	// contains filtered or unexported fields
}

A Selection is the rows chosen in a List or a Table that lets the user choose several (ListState.Selection), held by the keys of their items (ListState.Key), of type K: the choice stays with its items as rows come, go and move. Without a Key, rows are their indices, of type int. Its zero value is empty. The keys of items gone from the list stay until removed.

type app struct {
	files  []File
	chosen ui.Selection[string] // their paths
	list   ui.ListState
}

app.list.Key = func(i int) any { return app.files[i].Path }
app.list.Selection = &app.chosen

func (*Selection[K]) Add

func (s *Selection[K]) Add(k K)

Add chooses the row of key k.

func (*Selection[K]) All

func (s *Selection[K]) All() iter.Seq[K]

All returns the keys of the rows chosen, in no order.

func (*Selection[K]) Clear

func (s *Selection[K]) Clear()

Clear chooses no row.

func (*Selection[K]) Has

func (s *Selection[K]) Has(k K) bool

Has reports whether the row of key k is chosen.

func (*Selection[K]) Len

func (s *Selection[K]) Len() int

Len returns how many rows are chosen.

func (*Selection[K]) Remove

func (s *Selection[K]) Remove(k K)

Remove takes the row of key k out of the choice.

type Selector

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

A Selector is what ListState.Selection takes: a *Selection.

type Services

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

Services provides persistent window services for custom controls and asynchronous work. It owns no frame data and does not retain the window. Clipboard and URL methods run on the UI thread; Invalidate may run on any goroutine. Models are still updated through Window.Update.

func (Services) ClipboardFormats

func (s Services) ClipboardFormats() []transfer.Format

ClipboardFormats lists the formats on the clipboard without reading them, as a paste decides what to read: an image comes as transfer.PNG whatever the system's format, which ReadClipboardData converts.

func (Services) Invalidate

func (s Services) Invalidate()

func (Services) OpenURL

func (s Services) OpenURL(url string)

func (Services) ReadClipboard

func (s Services) ReadClipboard() string

func (Services) ReadClipboardData

func (s Services) ReadClipboardData(formats ...transfer.Format) transfer.Data

ReadClipboardData reads the clipboard's representations of formats, as a rich text editor reads its own format, HTML and plain text to paste the richest it understands; nil formats read all. A clipboard without them gives an empty Data.

func (Services) WriteClipboard

func (s Services) WriteClipboard(text string)

func (Services) WriteClipboardData

func (s Services) WriteClipboardData(data transfer.Data)

WriteClipboardData puts data on the clipboard, each representation of its items in the system's formats, as a rich text editor copies its own format, HTML and plain text.

type ShaderInput

type ShaderInput struct {
	Uniforms, WideUniforms []uint32
	Images                 [4]*Bitmap
	// Blur, for a shader reading its backdrop, is the standard deviation
	// of the backdrop's blur, in pixels.
	Blur float32
}

ShaderInput is what the effect of a shader of package ui/shader reads: the words of its uniforms' lanes, the words a wide gamut reads in their place (nil when the same), from EffectWords, and up to four images, bitmaps or canvases' (nil for none).

type SortOrder

type SortOrder struct {
	Column     string
	Descending bool
}

SortOrder is how a table's rows are sorted: by the column whose ID is Column, in ascending order unless Descending.

type Span

type Span struct {
	Text          string
	Font          string // a family, as for Element.Font
	Size          float32
	Weight        int
	Italic        bool
	Color         Color
	Underline     bool
	WavyUnderline bool
	Strikethrough bool
	// DecorationColor and DecorationThickness are those of the span's
	// underline and strikethrough, as for Element.DecorationColor.
	DecorationColor     Color
	DecorationThickness float32
	// Background highlights the span, as search results are.
	Background Color
	// Radius rounds the corners of the Background, which then hugs the
	// span's glyphs, a little wider than them, rather than filling the
	// line, as code within text shows.
	Radius        float32
	LetterSpacing float32
	Features      string // as for Element.FontFeatures, comma separated
	Lang          string // the language, as for Element.Lang
	// ObjectWidth and ObjectHeight, when ObjectWidth is set, make each
	// rune of the span, an object replacement character (U+FFFC), an
	// inline object: a box of that size in DIPs standing on the baseline,
	// which lines break around and which draws nothing, where a rich text
	// editor draws an image (TextLayout.Objects).
	ObjectWidth, ObjectHeight float32
}

Span is a run of a RichText with a style of its own. What it leaves zero takes the style of the text around it, and Italic, Underline, WavyUnderline and Strikethrough only turn those on.

type SpringOptions

type SpringOptions struct {
	Duration                 time.Duration
	Bounce                   float64
	Mass, Stiffness, Damping float64
	Precision                float64
	Velocity                 float32
}

SpringOptions describe a spring, as one perceives it or physically.

Duration and Bounce describe it as SwiftUI and Motion do: Duration is about how long it takes to arrive (500 ms when zero), and Bounce how much it overshoots, from 0, settling without overshooting, toward 1, bouncing for ever; below 0 it arrives more slowly still.

Mass, Stiffness and Damping describe it physically instead, as react spring does (1, 170 and 26 when zero), when Stiffness or Damping is set; setting them with Duration or Bounce panics.

Precision is how close to its target, in the value's units, the spring rests there: 0.001 when zero. Velocity, in value units per second, is the velocity the value takes when its target changes in the call, as that of a pointer letting go of what it dragged (DragEnded); zero keeps the value's own.

type TableColumn

type TableColumn struct {
	// Title heads the column. ID identifies it among the others, for the
	// order and the widths the user gives the columns (ListState.Columns)
	// and for the sort (ListState.Sort and SortBy): the Title when empty.
	Title, ID string
	// Width is the column's width in DIPs, or 0 to share the room the
	// others leave. The user resizes the column by dragging the right edge
	// of its header, between MinWidth and MaxWidth (none for 0), and fits
	// it to its cells with a double click there.
	Width, MinWidth, MaxWidth float32
	// Align aligns the content of its cells.
	Align Align
	// Sortable lets a click on the column's header sort the rows by it,
	// with ListState.Sort or SortBy.
	Sortable bool
	// Fixed keeps the column where it is and as wide as it is: the user
	// neither moves nor resizes it.
	Fixed bool
	// RowHeader marks a column of row headers, as a spreadsheet's row
	// numbers: in a table choosing cells (ListState.CellSelect), a click or
	// a drag on its cells chooses whole rows, with every column, and a
	// click on its header chooses every row. It does not sort, and is
	// never Cells.Cursor.
	RowHeader bool
}

TableColumn describes a column of a Table.

type TableLayout

type TableLayout struct {
	Order  []string
	Widths map[string]float32
}

TableLayout is the order and the widths the user gave the columns of a Table, by their IDs. Columns it does not name keep the order and the widths the table gives them.

type TabsParts

type TabsParts struct {
	List Element
	// contains filtered or unexported fields
}

TabsParts contains checked handles for the parts of a custom widget.

func TabsBase

func TabsBase(c *Context, selected *int, n int) TabsParts

TabsBase creates a list of n tabs without a look, of which *selected is the index of the one chosen. A click chooses a tab, as do the arrows, Home and End while one has the keyboard focus, which follows the choice; List's Changed reports a new choice. Build the tabs in List with Tab:

tabs := ui.TabsBase(c, &app.tab, len(names))
tabs.List.Gap(4).Children(func() {
	for i, name := range names {
		tab := tabs.Tab(i).Padding(6, 12).Radius(6)
		if i == app.tab {
			tab.Background(c.Theme().Surface)
		}
		tab.Children(func() { ui.Text(c, name) })
	}
})

Tabs is TabsBase with the theme's look.

func (TabsParts) Tab

func (_handle TabsParts) Tab(i int) Element

Tab creates tab i of the list: a row that takes the focus and chooses i when clicked. Style it from whether i is the one chosen.

type Tester

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

Tester runs a view without a window, as a test drives it: it renders frames in memory and sends the view pointer and keyboard input, between which it settles the frames the view asks for.

Its clock stands still unless the test moves it with Advance, so what depends on time (animations, Context.After, the clicks that make a double click, typing that undoes in one step, tooltips) does the same however fast the machine runs the test.

func NewTester

func NewTester(view func(c *Context), width int, height int) *Tester

NewTester starts testing view in a window of width×height DIPs. Two elements given one key under one parent make it panic where the second was given, as apps only log it.

func (*Tester) Advance

func (t *Tester) Advance(d time.Duration)

Advance moves the Tester's clock on by d, running the frames due meanwhile at their times: one each refresh while something moves, and those of After and Painter.After when they come due. An animation of 200 ms is a quarter of the way after Advance(50 * time.Millisecond), and done after another Advance(150 * time.Millisecond).

func (*Tester) Announcements

func (t *Tester) Announcements() []string

Announcements returns what the view asked screen readers to read out (Context.Announce), as a Router the titles of the pages it showed, and forgets it.

func (*Tester) ChooseMenuItem

func (t *Tester) ChooseMenuItem(path ...string) error

ChooseMenuItem chooses the item of the context menu shown labeled with the last of path, in the submenus the others label, and closes the menu.

func (*Tester) Click

func (t *Tester) Click(s string) error

Click clicks the center of the element showing text or labeled s. It returns an error when no element shows s, or when the element's center is outside the window, where the click would land on nothing.

func (*Tester) ClickAt

func (t *Tester) ClickAt(x, y float32)

ClickAt clicks at (x, y), in DIPs.

func (*Tester) ClickAtWith

func (t *Tester) ClickAtWith(mods Modifiers, x, y float32)

ClickAtWith clicks at (x, y), in DIPs, holding the modifier keys mods: a web view that takes the pointer there (WebViewAt) takes the click.

func (*Tester) ClickWith

func (t *Tester) ClickWith(mods Modifiers, s string) error

ClickWith clicks the center of the element showing text or labeled s holding the modifier keys mods, as a Shift-click.

func (*Tester) Clipboard

func (t *Tester) Clipboard() string

Clipboard returns the text the view copied; SetClipboard sets the text it pastes.

func (*Tester) ClipboardData

func (t *Tester) ClipboardData() transfer.Data

ClipboardData returns what the view copied with Services.WriteClipboardData, or the text it copied; SetClipboardData puts data on the clipboard, as another app copies HTML.

func (*Tester) CloseMenu

func (t *Tester) CloseMenu()

CloseMenu closes the context menu shown without choosing an item.

func (*Tester) Command

func (t *Tester) Command(name string)

Command performs an edit command of the menus, as Copy of the Edit menu: "copy", "cut", "paste", "pasteAndMatchStyle", "selectAll", "undo", "redo" or "delete", or a Format menu's, as "bold" or "alignCenter".

func (*Tester) Compose

func (t *Tester) Compose(text string, caret int)

Compose shows text as an input method's composition, with its caret at rune caret, as while typing in Chinese or Japanese; an empty text ends it. Type commits the text. Nothing is composed while the focused element turned input methods off (InputMethod), as on the desktop.

func (*Tester) Cursor

func (t *Tester) Cursor() Cursor

Cursor returns the pointer shape the view shows.

func (*Tester) DropFiles added in v0.1.8

func (t *Tester) DropFiles(x, y float32, paths ...string) bool

DropFiles drops files dragged from another app at (x, y), as from Finder, and reports whether an element took them (DroppedFiles).

func (*Tester) FailOpenURL

func (t *Tester) FailOpenURL(err error)

FailOpenURL makes the links the view opens from now on fail with err, as those no app opens, or opens them again for nil.

func (*Tester) Find

func (t *Tester) Find(s string) (Rect, bool)

Find returns the box of the first element showing text s, or labeled s.

func (*Tester) Focused

func (t *Tester) Focused(s string) bool

Focused reports whether the element showing text or labeled s, or its container, has the keyboard focus.

func (*Tester) Frame

func (t *Tester) Frame()

Frame renders another frame, as when the view's state changed.

func (*Tester) FramePending

func (t *Tester) FramePending() bool

FramePending reports whether the view still asks for a frame, as one that animates or never settles does after an input or Frame. The frames of After and Painter.After wait for Advance to reach their time, as the clock stands still until then.

func (*Tester) HasText

func (t *Tester) HasText(s string) bool

HasText reports whether the last frame shows a text containing s.

func (*Tester) HoldModifiers

func (t *Tester) HoldModifiers(mods Modifiers)

HoldModifiers presses or lets go of modifier keys on their own, as holding Cmd does, leaving mods held.

func (*Tester) Image

func (t *Tester) Image() *image.RGBA

Image returns the last frame.

func (*Tester) Key

func (t *Tester) Key(mods Modifiers, key Key)

Key presses a key with modifiers.

func (*Tester) KeyAt

func (t *Tester) KeyAt(mods Modifiers, physical Key)

KeyAt presses a key that the active layout does not type as a US key (Key is KeyUnknown), at position physical of an ANSI US keyboard, as S is pressed on a Cyrillic layout.

func (*Tester) KeyDown

func (t *Tester) KeyDown(key Key)

KeyDown presses a key and holds it, as a player holds a key that walks, until KeyUp.

func (*Tester) KeyUp

func (t *Tester) KeyUp(key Key)

KeyUp releases a key KeyDown held.

func (*Tester) Menu

func (t *Tester) Menu() []string

Menu returns the labels of the items of the context menu shown, "-" for separators, or nil when none is.

func (*Tester) Move

func (t *Tester) Move(x, y float32)

Move moves the pointer to (x, y).

func (*Tester) Now

func (t *Tester) Now() time.Time

Now returns the Tester's time, that of its next frame, which stands still until Advance moves it.

func (*Tester) OpenedURLs

func (t *Tester) OpenedURLs() []string

OpenedURLs returns the links the view opened.

func (*Tester) Pinch added in v0.1.8

func (t *Tester) Pinch(x, y, scale float32)

Pinch zooms by scale with the pointer at (x, y), as pinching a touchpad does (InputZoom).

func (*Tester) Press

func (t *Tester) Press(x, y float32)

Press presses (x, y) without releasing; Release releases it.

func (*Tester) Release

func (t *Tester) Release(x, y float32)

Release releases the pointer at (x, y).

func (*Tester) RightClick

func (t *Tester) RightClick(s string) error

RightClick clicks the center of the element showing text or labeled s with the secondary button. Like Click, it returns an error when no element shows s or its center is outside the window.

func (*Tester) RightClickAt

func (t *Tester) RightClickAt(x, y float32)

RightClickAt clicks at (x, y), in DIPs, with the secondary button.

func (*Tester) Scroll

func (t *Tester) Scroll(x, y, dx, dy float32)

Scroll scrolls by dx, dy DIPs with the pointer at (x, y), as a touchpad does: at once.

func (*Tester) SetClipboard

func (t *Tester) SetClipboard(s string)

SetClipboard sets the clipboard's text.

func (*Tester) SetClipboardData

func (t *Tester) SetClipboardData(d transfer.Data)

func (*Tester) SetDark

func (t *Tester) SetDark(dark bool)

SetDark switches between the light and the dark appearance.

func (*Tester) SetDirection

func (t *Tester) SetDirection(d Direction)

SetDirection lays the window out in d, as an app whose language reads so: RightToLeft lays it out from the right.

func (*Tester) SetFocused

func (t *Tester) SetFocused(focused bool)

SetFocused gives the window the keyboard, or takes it away, as when the user switches to another window.

func (*Tester) SetLocale

func (t *Tester) SetLocale(tag string)

SetLocale makes tag the language the app shows, as golet.App.SetLocale does: the view reads it with Context.Locale, and text without a language of its own is in it. A Tester starts with none, "", which draws text as the system does by default.

func (*Tester) SetPreferences

func (t *Tester) SetPreferences(p Preferences)

SetPreferences changes the desktop's settings that controls follow, as the user does in the system's settings.

func (*Tester) SetRegion

func (t *Tester) SetRegion(r i18n.Region)

SetRegion changes the user's regional formats, which the view reads with Context.Region, as the user does in the system's settings. A Tester starts with the zero Region.

func (*Tester) SetScale

func (t *Tester) SetScale(scale float32)

SetScale sets the device pixels per DIP.

func (*Tester) SetSize

func (t *Tester) SetSize(width, height int)

SetSize resizes the window.

func (*Tester) SetTitleBar

func (t *Tester) SetTitleBar(bar TitleBar)

SetTitleBar sets the room the window controls of a window with a hidden title bar take, which Context.TitleBar returns.

func (*Tester) SetVibrancy

func (t *Tester) SetVibrancy(shows bool)

SetVibrancy sets whether the window shows a material where the view draws no background, which Context.Vibrancy returns.

func (*Tester) TextCaret

func (t *Tester) TextCaret() (Rect, bool)

TextCaret returns where input methods compose, and whether one would: the caret of the focused text input, or of an element's TextCaret, and not while it turned them off (InputMethod).

func (*Tester) TextInputActive

func (t *Tester) TextInputActive() (active, noInputMethod bool)

TextInputActive reports whether the focused element takes text, typed or composed (HandleTextInput, TextCaret), and whether it turned input methods off (InputMethod), as the window tells the system.

func (*Tester) Texts

func (t *Tester) Texts() []string

Texts returns the texts of the last frame, in order.

func (*Tester) Type

func (t *Tester) Type(s string)

Type types text into the focused text input.

func (*Tester) TypeKey

func (t *Tester) TypeKey(mods Modifiers, key Key, text string)

TypeKey presses a key that types text, as a keyboard does: the key goes down, the text comes, then the key goes up.

func (*Tester) WebViewAt

func (t *Tester) WebViewAt(x, y float32) NativeWebView

WebViewAt returns the web view (WebView) that takes the pointer at (x, y), as the window shows it: where the last frame showed it and painted nothing over it that takes the pointer; nil for none.

func (*Tester) Wheel

func (t *Tester) Wheel(x, y, dx, dy float32)

Wheel scrolls by dx, dy DIPs with the pointer at (x, y), as a notch of a mouse wheel does: a scroll container glides there over a moment, which advancing the clock (Advance) shows.

type TextAffinity

type TextAffinity = text.Affinity

TextAffinity chooses a caret's preceding or following logical edge. Bidi boundaries and soft wraps can give the same index two visual positions.

type TextBuffer

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

TextBuffer stores editable UTF-8 text in an indexed, persistent tree. Small edits copy bounded chunks and tree paths, not the whole document. Rune offsets are used by Slice/Replace, matching Element.TextSelection; UTF16Offset/RuneOffset and TextForRange bridge native input coordinates. The zero value is an empty buffer. Methods are safe from any goroutine. Schedule edits with Window.Update to invalidate a view showing the buffer.

func NewTextBuffer

func NewTextBuffer(s string) *TextBuffer

NewTextBuffer creates indexed storage owning its text chunks. A small surviving fragment cannot pin the original large input string.

func (*TextBuffer) ByteLen

func (b *TextBuffer) ByteLen() int

func (*TextBuffer) Len

func (b *TextBuffer) Len() int

func (*TextBuffer) LineCount

func (b *TextBuffer) LineCount() int

func (*TextBuffer) Replace

func (b *TextBuffer) Replace(start, end int, s string)

Replace replaces a half-open rune range, clamping it to the document.

func (*TextBuffer) ReplaceUTF16

func (b *TextBuffer) ReplaceUTF16(r TextInputRange, s string) TextInputRange

ReplaceUTF16 adjusts surrogate interiors down to whole runes, replaces the range, and returns the actual old UTF-16 range it replaced.

func (*TextBuffer) Restore

func (b *TextBuffer) Restore(s TextSnapshot)

Restore adopts a snapshot in constant time and advances the version.

func (*TextBuffer) RuneOffset

func (b *TextBuffer) RuneOffset(index int) int

func (*TextBuffer) Set

func (b *TextBuffer) Set(s string)

Set replaces the document. Existing snapshots retain their own version.

func (*TextBuffer) Slice

func (b *TextBuffer) Slice(start, end int) string

func (*TextBuffer) Snapshot

func (b *TextBuffer) Snapshot() TextSnapshot

func (*TextBuffer) String

func (b *TextBuffer) String() string

String materializes the document for export. Controls do not call it during ordinary editing; Slice and WriteTo avoid that full allocation.

func (*TextBuffer) TextForRange

func (b *TextBuffer) TextForRange(r TextInputRange) (string, TextInputRange)

func (*TextBuffer) UTF16Len

func (b *TextBuffer) UTF16Len() int

func (*TextBuffer) UTF16Offset

func (b *TextBuffer) UTF16Offset(index int) int

func (*TextBuffer) Version

func (b *TextBuffer) Version() uint64

func (*TextBuffer) WriteTo

func (b *TextBuffer) WriteTo(w io.Writer) (int64, error)

type TextCaretPosition

type TextCaretPosition struct {
	Index    int
	Affinity TextAffinity
}

TextCaretPosition retains a UTF-16 index and its visual affinity.

type TextInputClient

type TextInputClient interface {
	TextForRange(TextInputRange) (string, TextInputRange)
	Selection() TextInputSelection
	MarkedRange() (TextInputRange, bool)
	ReplaceText(*TextInputRange, string)
	SetMarkedText(*TextInputRange, string, TextInputRange)
	UnmarkText()
	BoundsForRange(TextInputRange) (Rect, TextInputRange, bool)
	IndexForPoint(Point) (int, bool)
}

TextInputClient is an application-owned text-input target. It provides native input methods with document queries, composition and geometry; it owns the text, selection, marked range, editing policy and undo history. Pass a pointer to your client state. Callbacks run on the UI thread, as HandleInput does, and must not block on work requiring that thread. Keep the client alive across frames.

All ranges count UTF-16 code units of the current document, including its marked text. TextForRange clamps/adjusts requested ranges to valid text and returns the actual range. BoundsForRange returns element-relative geometry and the actual range represented, or false for unavailable/offscreen text. IndexForPoint takes an element-relative point and returns a UTF-16 offset.

A nil replacement range means the current marked range, if present, otherwise the selection. SetMarkedText's selected range is relative to the new marked text. ReplaceText commits and clears preedit; UnmarkText clears marked status, retaining the document's text. Selection is queried again after every mutation, before the next native event.

type TextInputRange

type TextInputRange = platform.TextRange

TextInputRange is a half-open range of UTF-16 code units. These are the units of native text services and can be converted at the storage boundary. They do not prescribe the client's buffer, grapheme or selection model.

type TextInputSelection

type TextInputSelection = platform.TextSelection

TextInputSelection is the primary selection reported to native input methods. Reversed places its caret at Range.Start. An editor can keep additional cursors or discontiguous ranges in its own state.

type TextKey

type TextKey struct {
	Key  Key
	Mods Modifiers
	// contains filtered or unexported fields
}

A TextKey is a key pressed in a text input, as OnTextKey's fn sees it. It is valid while fn runs: Text and SetText panic after fn returns.

func (TextKey) SetText

func (k TextKey) SetText(s string)

SetText replaces the text of the input, and its bound value, as the app does by setting the value as the view is built: a composer clears the draft it sent, Up puts the last message back. Writing the bound value from fn is not enough, as the editor writes what it holds over it.

func (TextKey) Text

func (k TextKey) Text() string

Text returns the text of the input as the key comes, with what was typed before it, which may be ahead of the bound value: that takes what is typed as the next frame is built.

type TextLayout

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

TextLayout is retained shaped text for a custom text control. It owns font and geometry results, not editable document state. Cache layouts of the paragraphs or lines you display, and replace only those affected by an edit. Its geometry methods are safe from any goroutine. Drawing uses a Painter during the view's frame. Offsets are UTF-16, matching TextInputClient.

func ShapeRichText

func ShapeRichText(spans []Span, font Font, width float32) *TextLayout

ShapeRichText shapes the existing display-only Span styles into retained geometry, so an application-owned rich editor can render its own runs.

func ShapeRichTextWith

func ShapeRichTextWith(spans []Span, font Font, shape TextShape) *TextLayout

ShapeRichTextWith shapes spans as ShapeRichText does, laid out as shape says: a rich text editor aligns its paragraphs.

func ShapeText

func ShapeText(s string, font Font, width float32) *TextLayout

ShapeText shapes text with the system's fonts, fallback, bidi and line breaking, wrapping at width DIPs (zero only breaks at newlines). It does not retain a copy of an editor document or install keyboard/editing behavior.

func (*TextLayout) Caret

func (t *TextLayout) Caret(index int) Rect

Caret gives the caret rectangle at index, snapped to a whole grapheme.

func (*TextLayout) CaretAt

func (t *TextLayout) CaretAt(p TextCaretPosition) Rect

CaretAt returns the rectangle of the requested visual edge.

func (*TextLayout) IndexAt

func (t *TextLayout) IndexAt(point Point) int

IndexAt finds the nearest whole-grapheme caret in visual layout order.

func (*TextLayout) MoveCaret

func (t *TextLayout) MoveCaret(p TextCaretPosition, direction int) TextCaretPosition

MoveCaret moves one visual grapheme left (negative) or right (positive).

func (*TextLayout) NextBoundary

func (t *TextLayout) NextBoundary(index int) int

func (*TextLayout) Objects

func (t *TextLayout) Objects() []TextObject

Objects returns the inline objects of the layout, in the order of the text, where a rich text editor draws its attachments.

func (*TextLayout) PositionAt

func (t *TextLayout) PositionAt(point Point) TextCaretPosition

PositionAt retains affinity while hit-testing whole graphemes.

func (*TextLayout) PreviousBoundary

func (t *TextLayout) PreviousBoundary(index int) int

PreviousBoundary and NextBoundary find neighboring whole-grapheme offsets for logical deletion and navigation. Visual selection policy remains with the application, which can keep multiple ranges and caret affinity.

func (*TextLayout) SelectionRanges

func (t *TextLayout) SelectionRanges(anchor, caret TextCaretPosition) []TextInputRange

SelectionRanges maps a visual gesture to logical UTF-16 ranges, preserving discontiguous selections through mixed-direction text. Supply these ranges to SelectionRects and to your buffer's copy/replacement operations.

func (*TextLayout) SelectionRects

func (t *TextLayout) SelectionRects(ranges ...TextInputRange) []Rect

SelectionRects returns the visual rectangles of one or more logical ranges, preserving gaps in bidi selections. An editor supplies its own range set and selection policy; the layout does not reduce it to one range.

func (*TextLayout) Size

func (t *TextLayout) Size() (float32, float32)

Size is the layout's extent in DIPs.

type TextLines

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

TextLines is where a text area laid out the lines of its text, kept in the app's state with TrackLines, for an app that paints beside them: line numbers by the first row of each line where the text wraps, or marks on runs of a line. The lines are the text's, between newlines; a line the area wraps takes several rows.

The area lays out only the lines in view, and those around them: the heights of the others are estimated until it shows them, as the scroll bar's are. Between a frame's build and its layout the lines are the last frame's, in the area's last width; in Draw and DrawOver, this frame's.

func (*TextLines) AppendRows

func (l *TextLines) AppendRows(dst []int, i int) []int

AppendRows appends where the rows of line i start to dst, as Rows.

func (*TextLines) At

func (l *TextLines) At(y float32) int

At returns the line at y in the content, as Top measures it: the first for y above it, the last for y past the end.

func (*TextLines) Count

func (l *TextLines) Count() int

Count returns how many lines the text has.

func (*TextLines) Height

func (l *TextLines) Height() float32

Height returns the height of the text: the top of the line after the last.

func (*TextLines) Rows

func (l *TextLines) Rows(i int) []int

Rows returns where the rows of line i start, in runes from the start of the line: [0] for a line on one row. It lays the line out if the area has not, which measures its height.

func (*TextLines) Top

func (l *TextLines) Top(i int) float32

Top returns the top of line i in the area's content, from the top of its first line: below the padding, and before the area scrolls.

type TextObject

type TextObject struct {
	Index int
	Rect  Rect
}

TextObject is an inline object of a TextLayout (Span.ObjectWidth): the UTF-16 offset of its object replacement character, and its box, standing on its line's baseline.

type TextRange

type TextRange struct {
	Start, End int
	Color      Color
	Weight     int
}

TextRange styles runes Start up to End of a text input's text: their color, when its alpha is not zero, and their weight, when Weight is set, as a message field shows the mentions in what is typed.

type TextShape

type TextShape struct {
	// Width wraps lines at it, in DIPs; zero only breaks at newlines.
	Width float32
	// Align aligns the lines within Width: Start (the default, the right
	// in right-to-left paragraphs, and of a right-to-left Direction),
	// Center or End.
	Align Align
	// Direction is that of the element the text shows in
	// (Context.Direction): right to left, lines start at the right, as
	// those of Text, and paragraphs without a strongly directional
	// character, as an empty one, read right to left. The others read in
	// the direction of their first strong character either way.
	Direction Direction
}

TextShape is how ShapeRichTextWith lays text out.

type TextSnapshot

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

TextSnapshot is an immutable, inexpensive view of a buffer. It shares unchanged chunks and can be read concurrently with further edits.

func (TextSnapshot) ByteLen

func (s TextSnapshot) ByteLen() int

func (TextSnapshot) Len

func (s TextSnapshot) Len() int

func (TextSnapshot) Line

func (s TextSnapshot) Line(line int) string

func (TextSnapshot) LineAt

func (s TextSnapshot) LineAt(index int) int

func (TextSnapshot) LineCount

func (s TextSnapshot) LineCount() int

func (TextSnapshot) LineRange

func (s TextSnapshot) LineRange(line int) (int, int)

LineRange returns a line's rune offsets, excluding its following newline. The terminal empty line after a newline is counted; line indices clamp.

func (TextSnapshot) RuneOffset

func (s TextSnapshot) RuneOffset(index int) int

func (TextSnapshot) Slice

func (s TextSnapshot) Slice(start, end int) string

func (TextSnapshot) String

func (s TextSnapshot) String() string

func (TextSnapshot) TextForRange

func (s TextSnapshot) TextForRange(r TextInputRange) (string, TextInputRange)

func (TextSnapshot) UTF16Len

func (s TextSnapshot) UTF16Len() int

func (TextSnapshot) UTF16Offset

func (s TextSnapshot) UTF16Offset(index int) int

func (TextSnapshot) Version

func (s TextSnapshot) Version() uint64

func (TextSnapshot) WriteTo

func (s TextSnapshot) WriteTo(w io.Writer) (int64, error)

type Theme

type Theme struct {
	Dark bool
	// Optional materials replace styled control and panel backgrounds.
	// Nil keeps the ordinary solid theme. Materials belong to the caller;
	// core UI never imports a renderer plugin. High contrast uses solid fills.
	ControlMaterial Material
	AccentMaterial  Material
	PanelMaterial   Material
	// Background fills the window.
	Background Color
	// Surface is the face of buttons, inputs and other controls;
	// SurfaceHover and SurfacePressed while hovered or pressed.
	Surface        Color
	SurfaceHover   Color
	SurfacePressed Color
	// Border outlines cards, buttons and popovers.
	Border Color
	// InputBorder outlines editable fields; zero falls back to Border.
	InputBorder Color
	// Sidebar fills navigation panels; zero falls back to Surface.
	Sidebar Color
	// Text and TextMuted color text; TextMuted is for secondary text and
	// placeholders.
	Text      Color
	TextMuted Color
	// Accent colors primary buttons, checked controls and focus rings;
	// AccentText is text on it.
	Accent        Color
	AccentHover   Color
	AccentPressed Color
	AccentText    Color
	Danger        Color
	// Warning and Success color what calls for attention and what went
	// well, as a Meter's levels.
	Warning Color
	Success Color
	// Selection highlights selected text.
	Selection Color
	// Focus is the ring around the control with the keyboard focus.
	Focus Color
	// Inverse fills tooltips and toasts, the theme turned over so that
	// they stand out from what they are over: dark in a light theme, light
	// in a dark one. InverseText is text on it. Left zero, they are Text
	// and Background.
	Inverse     Color
	InverseText Color
	// Scrollbar colors scroll bar thumbs, ScrollbarWidth DIPs wide (6 by
	// default; 0 is 6).
	Scrollbar      Color
	ScrollbarWidth float32
	// Radius rounds the corners of controls.
	Radius float32
	// Spacing is the unit of the room widgets leave inside and between
	// their parts: their paddings and gaps, and the sizes of check boxes,
	// switches, sliders and the rows of tables and trees, are multiples
	// of it. 4 by default: 3 makes widgets compact, 5 roomy; 0 is 4.
	Spacing float32
	// FontSize is the size of text, Font its family ("" is the system's).
	FontSize float32
	Font     string
}

Theme holds the colors and metrics widgets use. Change a copy of LightTheme or DarkTheme and set it with Context.SetTheme.

func DarkTheme

func DarkTheme() *Theme

DarkTheme returns the theme for a dark appearance.

func LightTheme

func LightTheme() *Theme

LightTheme returns the neutral shadcn palette for a light appearance. Colors are precomputed sRGB equivalents of the shadcn OKLCH tokens, keeping gamut conversion out of the default startup path.

func ShadcnTheme

func ShadcnTheme(dark bool) *Theme

ShadcnTheme returns the neutral shadcn palette with 14 DIP typography and soft, Maia-inspired corners. It shares LightTheme/DarkTheme's semantic colors. The returned value belongs to the caller: create it once, customize it and pass it to Context.SetTheme. No CSS, JavaScript or webview is required.

func (*Theme) Rem

func (t *Theme) Rem(n float32) float32

Rem returns n times the theme's FontSize, as CSS's rem, to size elements with the text.

func (*Theme) Space

func (t *Theme) Space(n float32) float32

Space returns n units of the theme's Spacing, to size elements of your own in step with the widgets: ui.Column(c).Gap(t.Space(2)).

type Timeline

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

A Timeline plays several tweens along one playhead, so that motion that belongs together is written, controlled and tested together: a card arriving while its title fades in, rows following one another, a small bounce after the card lands. It coordinates the motion already in Golet: a tween returns the value it shows in this frame, and the view gives it to a transform, a pose or a value, as it would give one of AnimateTo's.

card := ui.Column(c)
tl := card.Timeline("intro", ui.TimelineOptions{Run: app.opened})
x := tl.Tween(ui.Tween{From: -200, To: 0, Duration: 400 * time.Millisecond})
y := tl.Tween(ui.Tween{From: 20, To: 0, Duration: 300 * time.Millisecond},
	ui.AfterPrevious(-150*time.Millisecond))
card.Translate(x, y)

An element keeps its timelines as it keeps its Keyframes, from frame to frame while the view builds it, and they go with it: build a timeline in the same order every frame, and change Run to play it again, or a changed one. A *Timeline is valid only while the view builds the frame it was returned in: ask the element for it again in the next.

func (*Timeline) Arrived

func (t *Timeline) Arrived() bool

Arrived is true in the one frame in which the timeline came to rest, for the view to go on, as Element.Arrived is.

func (*Timeline) Duration

func (t *Timeline) Duration() time.Duration

Duration is how long the timeline plays: the end of its last tween, without its repeats.

func (*Timeline) Label

func (t *Timeline) Label(name string, at ...Placement)

Label marks a time of the timeline for a tween to start at with AtLabel. With no placement it marks where the tween before it ends.

tl.Label("intro", ui.AtTime(0))
...
tl.Tween(ui.Tween{...}, ui.AtLabel("intro", 200*time.Millisecond))

func (*Timeline) Progress

func (t *Timeline) Progress() float32

Progress is how far the playhead is along the timeline, from 0 to 1.

func (*Timeline) Settled

func (t *Timeline) Settled() bool

Settled reports whether the timeline rests, at its end with its repeats played out, or at its start while it plays in Reverse, as Element.Settled does for a value.

func (*Timeline) Time

func (t *Timeline) Time() time.Duration

Time is where the playhead is, from the start of the timeline.

func (*Timeline) Tween

func (t *Timeline) Tween(tw Tween, at ...Placement) float32

Tween adds tw to the timeline where at places it, following the tween before it at once with no placement, and returns the value it shows in this frame: its From before its time, its To after it.

x := tl.Tween(ui.Tween{From: 0, To: 120, Duration: 300 * time.Millisecond})
y := tl.Tween(ui.Tween{From: 20, To: 0, Duration: 200 * time.Millisecond},
	ui.AfterPrevious(-150*time.Millisecond))

type TimelineOptions

type TimelineOptions struct {
	// Run restarts the timeline when it changes, so that a view plays it
	// again by counting: the value a callback or a piece of state gives.
	Run uint64
	// Repeat is how many more times the timeline plays after the first,
	// RepeatForever for as long as the view builds it.
	Repeat int
	// Alternate plays every other time backward.
	Alternate bool
	// Delay holds the timeline at its first value for a while before it
	// plays, and RepeatDelay the value it got to between plays.
	Delay, RepeatDelay time.Duration
	// Paused holds the playhead where it is, so that the time a paused
	// timeline spends is not time it played and it goes on from where it
	// held when it is not paused.
	Paused bool
	// Reverse plays the timeline backward from where the playhead is, to
	// its start, as a menu that closes the way it opened; a timeline that
	// Run plays over while Reverse is set plays from its end.
	Reverse bool
	// Seek holds the playhead at a time of the timeline, and Progress at
	// a part of its duration, for a scrubber or a jump: while either is
	// set the timeline does not play, and it goes on from there when it
	// is not. Set one of them at most.
	Seek     *time.Duration
	Progress *float32
}

TimelineOptions says how a timeline plays. What it changes applies to the frame it is given in, except Run, which plays the timeline over when it changes, as KeyframeOptions.Run does.

type TitleBar

type TitleBar struct{ Height, Left, Right float32 }

TitleBar is the room the window controls take at the top of a window with a hidden title bar, in DIPs: they sit in a band of Height along the top edge, Left wide from the left edge and Right wide from the right.

type Toast

type Toast struct {
	// ID names the toast: adding one with the ID of a toast showing
	// changes that toast, which shows anew. AddToast makes one up when it
	// is empty.
	ID string
	// Title and Description are what the toast says, which screen readers
	// read out as it shows.
	Title, Description string
	// Type tells what kind of toast it is, as "error" or "success", for
	// the look to tell.
	Type string
	// Timeout is how long the toast shows: 4 seconds when zero, until it
	// is closed when negative. The time stops while the pointer rests on
	// the toasts, the keyboard focus is in them, or the window is in the
	// background.
	Timeout time.Duration
	// Action labels a button that runs OnAction, as Undo after deleting,
	// and closes the toast.
	Action   string
	OnAction func()
	// OnClose runs as the toast closes: its time is over, or the user, its
	// action or CloseToast closed it.
	OnClose func()
	// Data holds what else the look of the toast needs.
	Data any
}

Toast is a toast that AddToast shows, and that the view builds with ToastViewportBase to give toasts a look of its own.

type ToastParts

type ToastParts struct {
	Root Element
	// contains filtered or unexported fields
}

ToastParts contains checked handles for the parts of a custom widget.

func ToastBase

func ToastBase(c *Context, t Toast) ToastParts

ToastBase creates the toast t without a look, in the viewport of ToastViewportBase.

func (ToastParts) ActionButton

func (_handle ToastParts) ActionButton() Element

ActionButton creates a button without a look, as ButtonBase does, that runs the toast's OnAction and closes it. Give it children, as the toast's Action.

func (ToastParts) CloseButton

func (_handle ToastParts) CloseButton() Element

CloseButton creates a button without a look, as ButtonBase does, that closes the toast. Give it children, and a Label when they are not text.

func (ToastParts) Left

func (_handle ToastParts) Left() time.Duration

Left returns how long the toast shows still, to count down, or 0 for one that shows until it is closed. It does not move while the time of the toasts stops; ask for frames with Context.AnimationFrame to draw it moving.

type Track

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

Track sizes a column or a row of a grid: Fixed, Fr or FitContent.

func FitContent

func FitContent() Track

FitContent is a track as wide, or as high, as its content, within the room there is, as CSS's auto. Tracks beyond those a grid sets, such as the rows it adds for its children, fit their content.

func Fixed

func Fixed(v float32) Track

Fixed is a track of v DIPs.

func Fr

func Fr(f float32) Track

Fr is a track taking a share f of the room the other tracks leave, as CSS's minmax(0, <f>fr): tracks of Fr(1) share it equally, even where their content is wider. Where the grid's size is not set, as the height of a grid that grows with its rows, they are as large as their content asks, in proportion to f.

type Transform

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

Transform is a visual transform, in 2D, or in 3D seen in perspective. Its zero value is identity. It changes drawing and interaction, leaving the space reserved by layout unchanged. Build one with Translation, Scaling, Rotation and Skewing, and in 3D RotationX, RotationY and Perspective, and compose them with Then. Elements inherit their ancestors' transforms; each flattens what its 3D transform makes of it into its parent's plane, as CSS's flat transform-style.

func Perspective

func Perspective(distance float32) Transform

Perspective sees what the transforms before it put in 3D from distance DIPs in front of the origin, as CSS's perspective(): the shorter the distance, the deeper it looks; what goes away looks smaller. A distance of 800 or so looks natural for a card turning over.

func Rotation

func Rotation(degrees float32) Transform

Rotation rotates clockwise by degrees in the window's coordinate system.

func RotationX

func RotationX(degrees float32) Transform

RotationX turns content in 3D around the horizontal axis through its origin by degrees, its top going away for positive degrees, as CSS's rotateX. Seen without Perspective after it, it only looks shorter.

func RotationY

func RotationY(degrees float32) Transform

RotationY turns content in 3D around the vertical axis through its origin by degrees, its right side going away for positive degrees, as CSS's rotateY.

func Scaling

func Scaling(x, y float32) Transform

Scaling scales each axis; zero collapses it and negative values reflect it.

func Skewing

func Skewing(x, y float32) Transform

Skewing slants content by x degrees along the horizontal axis and y along the vertical, as CSS's skew(x, y).

func Translation

func Translation(x, y float32) Transform

Translation moves content by x and y DIPs.

func (Transform) Then

func (t Transform) Then(next Transform) Transform

Then applies t first, then next.

type Transition

type Transition uint8

Transition is how a Router's pages replace each other.

const (
	// TransitionAuto slides a page in from the right going deeper, as from
	// "/notes" to "/notes/42", and from the left back up; pages across, as
	// from "/notes" to "/settings", fade in. Where the desktop asks for less
	// motion, they all fade.
	TransitionAuto Transition = iota
	// TransitionFade fades pages in.
	TransitionFade
	// TransitionNone shows pages at once.
	TransitionNone
)

type Tween

type Tween struct {
	From, To float32
	Duration time.Duration
	Ease     Easing
}

A Tween is a value going from From to To along Ease over Duration, which a Timeline places and plays. With no Ease it eases out (EaseOut), as an Animation does.

Directories

Path Synopsis
Package chart builds charts in native UI without a look of their own, as headless libraries do on the web: scales that map data onto a plot and pick round ticks, a plot with axes around it, marks that are elements you style as any other, paths of lines, areas and pie slices for Draw functions, stacking, and a selection that the pointer and the keyboard move.
Package chart builds charts in native UI without a look of their own, as headless libraries do on the web: scales that map data onto a plot and pick round ticks, a plot with axes around it, marks that are elements you style as any other, paths of lines, areas and pie slices for Draw functions, stacking, and a selection that the pointer and the keyboard move.
Package editor is a code editor and a diff viewer for Golet's native UI, on package ui.
Package editor is a code editor and a diff viewer for Golet's native UI, on package ui.
Package shader draws with shaders an app writes: fragment shaders in Go's syntax, which run on the GPU, whichever renderer draws the window (Metal, Direct3D 11, OpenGL or WebGL 2), and on the CPU where none can.
Package shader draws with shaders an app writes: fragment shaders in Go's syntax, which run on the GPU, whichever renderer draws the window (Metal, Direct3D 11, OpenGL or WebGL 2), and on the CPU where none can.

Jump to

Keyboard shortcuts

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