ui

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 61 Imported by: 34 modules, 0 packages

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

Documentation

Overview

Package ui builds user interfaces that MyGo 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++
		}
	})
}

mygo.NewWindow(mygo.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; MyGo 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, the keys of keyboards that have them, and on
	// macOS swipes between pages. A Router takes them.
	KeyBack    = Key(platform.KeyBack)
	KeyForward = Key(platform.KeyForward)
)

Keys.

View Source
const (
	CodeUnknown         = KeyCode(platform.CodeUnknown)
	CodeKeyA            = KeyCode(platform.CodeKeyA)
	CodeKeyB            = KeyCode(platform.CodeKeyB)
	CodeKeyC            = KeyCode(platform.CodeKeyC)
	CodeKeyD            = KeyCode(platform.CodeKeyD)
	CodeKeyE            = KeyCode(platform.CodeKeyE)
	CodeKeyF            = KeyCode(platform.CodeKeyF)
	CodeKeyG            = KeyCode(platform.CodeKeyG)
	CodeKeyH            = KeyCode(platform.CodeKeyH)
	CodeKeyI            = KeyCode(platform.CodeKeyI)
	CodeKeyJ            = KeyCode(platform.CodeKeyJ)
	CodeKeyK            = KeyCode(platform.CodeKeyK)
	CodeKeyL            = KeyCode(platform.CodeKeyL)
	CodeKeyM            = KeyCode(platform.CodeKeyM)
	CodeKeyN            = KeyCode(platform.CodeKeyN)
	CodeKeyO            = KeyCode(platform.CodeKeyO)
	CodeKeyP            = KeyCode(platform.CodeKeyP)
	CodeKeyQ            = KeyCode(platform.CodeKeyQ)
	CodeKeyR            = KeyCode(platform.CodeKeyR)
	CodeKeyS            = KeyCode(platform.CodeKeyS)
	CodeKeyT            = KeyCode(platform.CodeKeyT)
	CodeKeyU            = KeyCode(platform.CodeKeyU)
	CodeKeyV            = KeyCode(platform.CodeKeyV)
	CodeKeyW            = KeyCode(platform.CodeKeyW)
	CodeKeyX            = KeyCode(platform.CodeKeyX)
	CodeKeyY            = KeyCode(platform.CodeKeyY)
	CodeKeyZ            = KeyCode(platform.CodeKeyZ)
	CodeDigit1          = KeyCode(platform.CodeDigit1)
	CodeDigit2          = KeyCode(platform.CodeDigit2)
	CodeDigit3          = KeyCode(platform.CodeDigit3)
	CodeDigit4          = KeyCode(platform.CodeDigit4)
	CodeDigit5          = KeyCode(platform.CodeDigit5)
	CodeDigit6          = KeyCode(platform.CodeDigit6)
	CodeDigit7          = KeyCode(platform.CodeDigit7)
	CodeDigit8          = KeyCode(platform.CodeDigit8)
	CodeDigit9          = KeyCode(platform.CodeDigit9)
	CodeDigit0          = KeyCode(platform.CodeDigit0)
	CodeEnter           = KeyCode(platform.CodeEnter)
	CodeEscape          = KeyCode(platform.CodeEscape)
	CodeBackspace       = KeyCode(platform.CodeBackspace)
	CodeTab             = KeyCode(platform.CodeTab)
	CodeSpace           = KeyCode(platform.CodeSpace)
	CodeMinus           = KeyCode(platform.CodeMinus)
	CodeEqual           = KeyCode(platform.CodeEqual)
	CodeBracketLeft     = KeyCode(platform.CodeBracketLeft)
	CodeBracketRight    = KeyCode(platform.CodeBracketRight)
	CodeBackslash       = KeyCode(platform.CodeBackslash)
	CodeSemicolon       = KeyCode(platform.CodeSemicolon)
	CodeQuote           = KeyCode(platform.CodeQuote)
	CodeBackquote       = KeyCode(platform.CodeBackquote)
	CodeComma           = KeyCode(platform.CodeComma)
	CodePeriod          = KeyCode(platform.CodePeriod)
	CodeSlash           = KeyCode(platform.CodeSlash)
	CodeCapsLock        = KeyCode(platform.CodeCapsLock)
	CodeF1              = KeyCode(platform.CodeF1)
	CodeF2              = KeyCode(platform.CodeF2)
	CodeF3              = KeyCode(platform.CodeF3)
	CodeF4              = KeyCode(platform.CodeF4)
	CodeF5              = KeyCode(platform.CodeF5)
	CodeF6              = KeyCode(platform.CodeF6)
	CodeF7              = KeyCode(platform.CodeF7)
	CodeF8              = KeyCode(platform.CodeF8)
	CodeF9              = KeyCode(platform.CodeF9)
	CodeF10             = KeyCode(platform.CodeF10)
	CodeF11             = KeyCode(platform.CodeF11)
	CodeF12             = KeyCode(platform.CodeF12)
	CodePrintScreen     = KeyCode(platform.CodePrintScreen)
	CodeScrollLock      = KeyCode(platform.CodeScrollLock)
	CodePause           = KeyCode(platform.CodePause)
	CodeInsert          = KeyCode(platform.CodeInsert)
	CodeHome            = KeyCode(platform.CodeHome)
	CodePageUp          = KeyCode(platform.CodePageUp)
	CodeDelete          = KeyCode(platform.CodeDelete)
	CodeEnd             = KeyCode(platform.CodeEnd)
	CodePageDown        = KeyCode(platform.CodePageDown)
	CodeArrowRight      = KeyCode(platform.CodeArrowRight)
	CodeArrowLeft       = KeyCode(platform.CodeArrowLeft)
	CodeArrowDown       = KeyCode(platform.CodeArrowDown)
	CodeArrowUp         = KeyCode(platform.CodeArrowUp)
	CodeNumLock         = KeyCode(platform.CodeNumLock)
	CodeNumpadDivide    = KeyCode(platform.CodeNumpadDivide)
	CodeNumpadMultiply  = KeyCode(platform.CodeNumpadMultiply)
	CodeNumpadSubtract  = KeyCode(platform.CodeNumpadSubtract)
	CodeNumpadAdd       = KeyCode(platform.CodeNumpadAdd)
	CodeNumpadEnter     = KeyCode(platform.CodeNumpadEnter)
	CodeNumpad1         = KeyCode(platform.CodeNumpad1)
	CodeNumpad2         = KeyCode(platform.CodeNumpad2)
	CodeNumpad3         = KeyCode(platform.CodeNumpad3)
	CodeNumpad4         = KeyCode(platform.CodeNumpad4)
	CodeNumpad5         = KeyCode(platform.CodeNumpad5)
	CodeNumpad6         = KeyCode(platform.CodeNumpad6)
	CodeNumpad7         = KeyCode(platform.CodeNumpad7)
	CodeNumpad8         = KeyCode(platform.CodeNumpad8)
	CodeNumpad9         = KeyCode(platform.CodeNumpad9)
	CodeNumpad0         = KeyCode(platform.CodeNumpad0)
	CodeNumpadDecimal   = KeyCode(platform.CodeNumpadDecimal)
	CodeIntlBackslash   = KeyCode(platform.CodeIntlBackslash)
	CodeContextMenu     = KeyCode(platform.CodeContextMenu)
	CodePower           = KeyCode(platform.CodePower)
	CodeNumpadEqual     = KeyCode(platform.CodeNumpadEqual)
	CodeF13             = KeyCode(platform.CodeF13)
	CodeF14             = KeyCode(platform.CodeF14)
	CodeF15             = KeyCode(platform.CodeF15)
	CodeF16             = KeyCode(platform.CodeF16)
	CodeF17             = KeyCode(platform.CodeF17)
	CodeF18             = KeyCode(platform.CodeF18)
	CodeF19             = KeyCode(platform.CodeF19)
	CodeF20             = KeyCode(platform.CodeF20)
	CodeF21             = KeyCode(platform.CodeF21)
	CodeF22             = KeyCode(platform.CodeF22)
	CodeF23             = KeyCode(platform.CodeF23)
	CodeF24             = KeyCode(platform.CodeF24)
	CodeAudioVolumeMute = KeyCode(platform.CodeAudioVolumeMute)
	CodeAudioVolumeUp   = KeyCode(platform.CodeAudioVolumeUp)
	CodeAudioVolumeDown = KeyCode(platform.CodeAudioVolumeDown)
	CodeNumpadComma     = KeyCode(platform.CodeNumpadComma)
	CodeIntlRo          = KeyCode(platform.CodeIntlRo)
	CodeKanaMode        = KeyCode(platform.CodeKanaMode)
	CodeIntlYen         = KeyCode(platform.CodeIntlYen)
	CodeConvert         = KeyCode(platform.CodeConvert)
	CodeNonConvert      = KeyCode(platform.CodeNonConvert)
	CodeLang1           = KeyCode(platform.CodeLang1)
	CodeLang2           = KeyCode(platform.CodeLang2)
	CodeLang3           = KeyCode(platform.CodeLang3)
	CodeLang4           = KeyCode(platform.CodeLang4)
	CodeControlLeft     = KeyCode(platform.CodeControlLeft)
	CodeShiftLeft       = KeyCode(platform.CodeShiftLeft)
	CodeAltLeft         = KeyCode(platform.CodeAltLeft)
	CodeSuperLeft       = KeyCode(platform.CodeSuperLeft)
	CodeControlRight    = KeyCode(platform.CodeControlRight)
	CodeShiftRight      = KeyCode(platform.CodeShiftRight)
	CodeAltRight        = KeyCode(platform.CodeAltRight)
	CodeSuperRight      = KeyCode(platform.CodeSuperRight)
)

Keys by position.

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 (
	// PointerMouse is a mouse, or a touchpad, which moves the pointer as
	// one does.
	PointerMouse = PointerType(platform.PointerMouse)
	// PointerPen is a pen on a tablet or a screen, its eraser too.
	PointerPen = PointerType(platform.PointerPen)
	// PointerTouch is a finger on a touchscreen.
	PointerTouch = PointerType(platform.PointerTouch)
)

Pointer devices.

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)
	// CursorProgress shows that the app is busy while it can still be
	// used, as over an element marked busy (aria-busy), and CursorWait
	// that it cannot be.
	CursorProgress = Cursor(platform.CursorProgress)
	CursorWait     = Cursor(platform.CursorWait)
	CursorHelp     = Cursor(platform.CursorHelp)
	// CursorCell selects cells, as of a spreadsheet.
	CursorCell = Cursor(platform.CursorCell)
	// CursorZoomIn and CursorZoomOut show that a click zooms, as over an
	// image.
	CursorZoomIn  = Cursor(platform.CursorZoomIn)
	CursorZoomOut = Cursor(platform.CursorZoomOut)
	// CursorAllScroll scrolls in every direction, as a middle-button
	// autoscroll does.
	CursorAllScroll = Cursor(platform.CursorAllScroll)
	// CursorNoDrop shows that what is dragged cannot be dropped here.
	CursorNoDrop = Cursor(platform.CursorNoDrop)
)

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 added in v0.2.5

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 added in v0.2.17

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.17

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 added in v0.2.1

func EaseIn(t float32) float32

EaseIn starts slowly (a cubic).

func EaseInOut added in v0.2.1

func EaseInOut(t float32) float32

EaseInOut starts and ends slowly (a cubic).

func EaseOut added in v0.2.1

func EaseOut(t float32) float32

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

func FocusedValue added in v0.3.0

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 ImageSize added in v0.7.2

func ImageSize(src ImageSource) (w, h float32)

ImageSize returns the size Image shows src at by default, in DIPs: a bitmap's pixels, the size an SVG says it has, or a texture's pixels as its last frame has them. It is 0×0 for nil.

func Linear added in v0.2.1

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.

The element owns what init made. When a frame no longer builds it, a value that is an io.Closer (T or *T has Close() error) is closed once, on the main thread, after that frame, as the web aborts an AbortController as an element is removed: a component cancels in Close the work it started, as a streaming request, a ticker or a subscription:

s := ui.Local(e, "stream", func() *stream { return startStream(url) })

An element leaving with an exit transition closes them once its exit ended, and every element as its window closes. A nil value is not closed, and Close's error is ignored. Keep a value the element must not close, as one the app shares, in the app's state.

func Nearest added in v0.4.5

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. Built inside the children of a Themed, they take its theme.

func Project added in v0.4.3

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. The fonts registered under a family make it up, apart from other fonts of their own family. A Tester's window draws them too.

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 added in v0.4.3

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 added in v0.5.0

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 added in v0.2.17

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 added in v0.2.17

func UTF16Len(s string) int

UTF16Len returns the number of native text offsets in s.

Types

type AccessInfo added in v0.8.0

type AccessInfo struct {
	// Role is the element's role, as Role set it or as its widget or what
	// it does gave it: never RoleAuto or RoleNone.
	Role Role
	// Name is the accessible name: the Label, or the text inside the
	// element. Value is its value, as a text field's text, the choice a
	// pop-up button shows, or what a slider reads (aria-valuetext).
	// Description is read after the name, as a tooltip or a field's
	// error, and Placeholder is what an empty text field shows.
	Name, Value, Description, Placeholder string
	// RoleDescription is what the app calls the role in its place
	// (aria-roledescription), as a "carousel" group; "" for the
	// platform's name of Role.
	RoleDescription string
	// Bounds is the element's visible box, in the window's DIPs as Find's.
	Bounds Rect
	// Checked is set on a check box, switch, radio button or menu item
	// that is on, and on a toggle button pressed (aria-checked,
	// aria-pressed); Mixed in its place on one partly on.
	Checked, Mixed bool
	// Expanded is set while what the element opens shows; Expandable on
	// an item of a tree with children.
	Expanded, Expandable bool
	// Selected is set on the tab chosen, on the items of a tree and the
	// rows of a list, a table or a grid chosen, and on the cells of a
	// table or a grid chosen with Checked (aria-selected), which are
	// Selectable where their list, table or grid chooses them;
	// Multiselectable is set on a list, a table or a grid choosing
	// several.
	Selected, Selectable, Multiselectable bool
	// Busy is set while the element's content is about to change
	// (aria-busy).
	Busy bool
	// Disabled is set on an element that takes no input, Invalid on one
	// whose value is not valid, as a field with an error.
	Disabled, Invalid bool
	// Focusable is set on an element that takes the keyboard focus, and
	// Focused on the one assistive technology has the focus on: the
	// element with it, or the option the arrows are on in a list or a
	// combobox that keeps it (ActiveDescendant).
	Focusable, Focused bool
	// ReadOnly, Multiline, Password and Search tell of a text field.
	ReadOnly, Multiline, Password, Search bool
	// Sort is the order a table's rows are sorted in by the column whose
	// header the element is (aria-sort), SortNone for others.
	Sort SortDirection
	// HasPopup is the kind of popup the element opens (aria-haspopup),
	// PopupNone for none.
	HasPopup Popup
	// Controls are the accessible names of the elements the element
	// controls (aria-controls), in the last frame, in the order Controls
	// gave them: Access finds each.
	Controls []string
	// DescribedBy are the accessible names of the elements describing the
	// element (aria-describedby), whose text Description holds, and
	// ErrorMessage those of the elements holding its error
	// (aria-errormessage), given while it is Invalid, in the order
	// DescribedBy and ErrorMessage gave them.
	DescribedBy, ErrorMessage []string
	// Vertical is set on a slider going up, a separator running up and
	// down, and an element told it is vertical (aria-orientation);
	// Horizontal on one told it runs across (Orientation). Segment is set
	// on a segment of a segmented control or a group of toggles.
	Vertical, Horizontal, Segment bool
	// Offscreen is set on an element built out of view, as the rows a
	// list builds beyond its edges.
	Offscreen bool
	// Current is the item the element is the current one of
	// (aria-current), CurrentNone for none.
	Current Current
	// AutoComplete is what the suggestions of a text field or a combo
	// box complete as the user types (aria-autocomplete),
	// AutoCompleteNone for none.
	AutoComplete AutoComplete
	// KeyShortcuts are the keys that press or focus the element
	// (aria-keyshortcuts), as the platform's menus write them and
	// separated by spaces: "⌘K" for Cmd+K on macOS, "Ctrl+K" elsewhere.
	KeyShortcuts string
	// Level is the rank of a heading, or how deep an item of a tree is,
	// from 1; 0 for other elements.
	Level int
	// PosInSet is the place of an item in its set, from 1, and SetSize
	// the size of the set, as a list's rows and the list have them; 0
	// when not given.
	PosInSet, SetSize int
	// RowCount and ColumnCount are how many rows and columns a table or
	// a grid has (aria-rowcount, aria-colcount), and RowIndex and
	// ColumnIndex the place of a row or a cell among them, from 1
	// (aria-rowindex, aria-colindex), as the app gave them; 0 when not
	// given.
	RowCount, ColumnCount, RowIndex, ColumnIndex int
	// RowSpan and ColumnSpan are how many rows and columns a cell covers
	// (aria-rowspan, aria-colspan), as its RowSpan and ColumnSpan set
	// them; 0 for one.
	RowSpan, ColumnSpan int
	// Min, Max and Now are the range and the value of a slider, progress
	// bar, meter or stepper (aria-valuemin, -valuemax and -valuenow), Now
	// below Min for progress of unknown length; Step is how far the keys
	// move the value, 0 for none.
	Min, Max, Now, Step float64
}

AccessInfo is what assistive technology sees of an element of the last frame (Tester.Access): its role, name, value and states, as the accessibility tree gives them to screen readers.

type AccordionParts added in v0.8.0

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

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

func AccordionBase added in v0.8.0

func AccordionBase(c *Context) AccordionParts

AccordionBase creates an accordion without a look: a column of sections, each a CollapsibleBase that Item makes, opening and closing on its own, whose headers Up and Down move the keyboard focus between, as do Home and End. Build the sections in Root:

acc := ui.AccordionBase(c)
acc.Root.Gap(4).Children(func() {
	for i := range app.sections {
		s := &app.sections[i]
		item := acc.Item(&s.open)
		item.Trigger.Padding(8, 12).Radius(6).Children(func() {
			ui.Text(c, s.title).Grow(1)
			ui.Icon(c, chevron).Rotate(180 * item.Progress())
		})
		item.Panel(func() { s.build(c) })
	}
})

Accordion is AccordionBase with the theme's look.

func (AccordionParts) Item added in v0.8.0

func (_handle AccordionParts) Item(open *bool) CollapsibleParts

Item creates a section of the accordion, open while *open: a CollapsibleBase, whose Trigger is its header, which a click opens and closes, as do Enter and Space, and the arrows, Home and End leave for the other sections' headers; Panel builds what shows below it while it is open. Assistive technology sees the header as a disclosure, expanded while open.

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 added in v0.2.8

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 added in v0.4.3

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
	// Oklab mixes the colors it moves (AnimateColor, and a Transition's
	// colors, those of an element of its Match and a ContentTransition's
	// text morphing) in the Oklab color space, as a gradient's Oklab
	// does, instead of in sRGB: between two saturated colors, the way
	// keeps their lightness and saturation rather than going through a
	// dull, darker middle.
	Oklab bool
	// NonMotion says that the value AnimateTo animates moves nothing on
	// screen, as an opacity, a blur or a crossfade: it still animates
	// while the desktop asks for less motion (Preferences.ReduceMotion),
	// as colors and a Transition's fades do, where other values go to
	// their targets at once. Leave it off for a position, a size, a
	// scale or a scroll. What MyGo moves itself (ScrollTo, a pose, a
	// Transition) knows what moves, and does not read it.
	NonMotion bool
}

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 AutoComplete added in v0.8.0

type AutoComplete uint8

AutoComplete is what the suggestions of a text input complete as the user types (Element.AutoComplete), as ARIA's aria-autocomplete says.

const (
	// AutoCompleteNone suggests nothing as the user types: the popup of
	// a combobox, if any, shows the same options whatever is typed.
	AutoCompleteNone AutoComplete = iota
	// AutoCompleteInline completes the text in place: the rest of the
	// value the input guesses is inserted after the caret, selected.
	AutoCompleteInline
	// AutoCompleteList shows a popup of the values that complete what
	// was typed, as the options of a Combobox or an Autocomplete.
	AutoCompleteList
	// AutoCompleteBoth shows the popup, and completes the text in place
	// with the option the arrows are on.
	AutoCompleteBoth
)

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. The bitmap keeps data, without a copy, to decode it again after ReleasePixels.

func NewBitmap

func NewBitmap(img image.Image) *Bitmap

NewBitmap converts img. The bitmap keeps no reference to img, unless ReleasePixels has it convert img again when it needs the pixels.

func (*Bitmap) Pixelated added in v0.4.7

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) ReleasePixels added in v0.7.0

func (b *Bitmap) ReleasePixels()

ReleasePixels drops the CPU pixels of a bitmap, those of its picture and of its levels, keeping the copies a GPU renderer uploaded: the bitmap draws as before. The pixels are made again when something needs them — a renderer that lost its textures or let one go, the CPU renderer, or a level for drawing the bitmap smaller — and a GPU renderer's upload drops them again: decoded again from the data DecodeBitmap took, or converted again from the image NewBitmap took, which the bitmap keeps from then on, without a copy. Either must stay as it was. A bitmap NewBitmap made of an image the app no longer keeps (or of a type other than package image's), a canvas's, or one Update changed has nothing else to make them from and keeps them. Call it once the bitmap has shown, on the main thread, as drawing does.

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 added in v0.4.0

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. UpdateYUV shows frames in Y′CbCr, as decoders give them, without converting them.

func (*Bitmap) UpdateYUV added in v0.9.0

func (b *Bitmap) UpdateYUV(img *YUVImage)

UpdateYUV shows img in place of the bitmap's picture, as Update does, for frames of video a decoder gives in Y′CbCr: the GPU uploads its planes, 1.5 bytes a pixel against RGBA's 4, and converts them as it samples them, so that showing a frame costs the CPU no conversion. The planes are taken as they are, without a copy, but for I420's chroma, which goes into a plane the bitmap keeps, interleaved as NV12's: don't change them until the next update. A renderer that draws on the CPU, and a capture, converts the picture as it needs it.

The bitmap shows the picture at its size, which the GPU scales as it samples it, without the halved copies of a bitmap's picture shown much smaller: have the decoder give the size the bitmap shows at, where it can. Call it on the main thread, in the view or through Window.Update. It panics on a picture its planes cannot hold, or of a format or a matrix it does not know.

type BorderStyle added in v0.2.1

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 added in v0.4.7

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 added in v0.4.7

func NewCanvas(w, h int) *Canvas

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

func (*Canvas) Bitmap added in v0.4.7

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 added in v0.4.7

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 added in v0.4.7

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

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

type CellsStyle added in v0.8.0

type CellsStyle struct {
	// Cell is the background of the cells of the block, and the border of
	// the cursor where it is out of the block.
	Cell Color
	// CellText is the color of their text and of the cursor's border in
	// the block, as AccentText is of chosen rows.
	CellText Color
	// Row is the background of the rows chosen.
	Row Color
	// Stripe is the background of every other row.
	Stripe Color
}

A CellsStyle paints the block of cells a Table chooses (CellSelect), and the rows chosen, in its own colors rather than the accent, as a spreadsheet does: the chosen cell stands out over its row, and the rows alternate.

grid.CellsStyle = ui.CellsStyle{
	Cell:     t.Accent,
	CellText: t.AccentText,
	Row:      t.Accent.Alpha(0.12),
	Stripe:   t.Text.Alpha(0.04),
}

A zero color paints none, leaving the theme's background, except where Cell is zero: the block then shows as chosen rows do, in the accent.

type CheckState added in v0.8.0

type CheckState uint8

CheckState is what a check box that can be mixed shows (CheckboxStateBase): unchecked, checked, or mixed, as one checking a group whose boxes differ.

const (
	CheckOff CheckState = iota
	CheckOn
	CheckMixed
)

type CollapsibleParts added in v0.2.5

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

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

func CollapsibleBase added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.15

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) MixOklab added in v0.8.0

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

MixOklab returns the color t of the way from c to o, mixed in the Oklab color space, as a gradient's Oklab mixes and CSS's color-mix(in oklab) does: between two saturated colors, the mix keeps their lightness and saturation, where Mix's, in sRGB, is duller and darker. A mix outside the sRGB gamut holds its wide color, as a color from Oklch does. As in CSS, the colors mix with premultiplied alpha: a color mixed with Transparent keeps its hue and fades, rather than darkening.

func (Color) Over

func (c Color) Over(base Color) Color

Over returns c composited over the opaque color base.

func (Color) SRGB added in v0.2.15

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 added in v0.6.0

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 added in v0.2.5

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

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

func ComboboxBase added in v0.2.5

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; tell it with AutoComplete when the options are those matching what was typed (AutoCompleteList).

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

func (_handle ComboboxParts) Open() bool

Open reports whether the popup shows.

func (ComboboxParts) Popup added in v0.2.5

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. A popup without options shows only while it holds something else to read, as a row saying that nothing matches, which assistive technology reads out as it appears:

if len(matches) == 0 {
	ui.Text(c, "No matches found").Padding(6, 10)
}

It returns the panel, or nil while it does not show.

func (ComboboxParts) SetOpen added in v0.2.5

func (_handle ComboboxParts) SetOpen(o bool)

SetOpen opens or closes the popup.

type ConicGradient added in v0.5.5

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 mygo.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 mygo.WindowOptions.Content:

mygo.NewWindow(mygo.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 mygo calls it.

type ContentTransition added in v0.4.3

type ContentTransition struct {
	Numeric, Down, Morph 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.

Morph moves the characters the old and the new text have in common from where they were to where they are, growing or shrinking to their size, those of the old text alone fading out and those of the new fading in, as Keynote's Magic Move by characters: words reflowing, a title rewritten, letters rearranged. Rich text morphs too: its characters go to the colors of their spans, and its lines and highlights fade. A text flying with a Transition's Match (Fly) morphs from the text of the element of its Match.

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 added in v0.2.15

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 added in v0.2.5

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 added in v0.2.15

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 added in v0.5.0

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 added in v0.4.3

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) FocusTakesText added in v0.8.0

func (_handle *Context) FocusTakesText() bool

FocusTakesText reports whether the element with the keyboard focus takes text, typed or composed: a text input or text area, or an editor of rich text or code, that is not read only, or an element that takes text itself (HandleTextInput, TextCaret). It is the web's guard of single-key shortcuts (isContentEditable, an input or a textarea, the role textbox): a command palette's letters step aside while a field takes them as text.

if !c.FocusTakesText() && c.Shortcut(0, ui.KeyK) {
	app.palette = true
}

It is false while the window does not have the keyboard, as the window tells the system's input methods then.

func (*Context) FocusWithin added in v0.3.0

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

func (*Context) Focused added in v0.3.0

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

func (*Context) Instant added in v0.7.4

func (_handle *Context) Instant() bool

Instant reports whether this frame shows animated values at once (DisableAnimations). Views read it to render a change settled in the same frames where its animations are disabled.

func (*Context) Invalidate

func (c *Context) Invalidate()

Invalidate requests a frame from any goroutine.

func (*Context) Key added in v0.3.0

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) KeyDown added in v0.8.0

func (_handle *Context) KeyDown(key Key) bool

KeyDown reports whether key is held down in the window, whichever element has the focus and whether or not one took the key, without taking it from them: a cheat sheet of shortcuts lights the keys held while its search field has the focus. A frame that reads it is drawn again as the keys held change. Keys count as shortcuts take them (a chord of a key the layout types no US key for, as S on a Cyrillic layout, by its position); the modifier keys are Modifiers'. A key whose press ran a menu item's shortcut went to the menu, not the window. The window lets go of every key as it loses the keyboard, whose releases go elsewhere.

func (*Context) KeysDown added in v0.8.0

func (_handle *Context) KeysDown() []Key

KeysDown returns the keys held down in the window, as KeyDown tells them, in the order they were pressed; nil while none is. A cheat sheet fades the rows of shortcuts that use none of them:

held := c.KeysDown()
for _, s := range app.shortcuts {
	row := shortcutRow(c, s)
	if len(held) > 0 && !s.usesAny(held) {
		row.Opacity(0.4)
	}
}

func (*Context) Locale added in v0.5.0

func (_handle *Context) Locale() string

Locale returns the language the app shows (mygo.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 added in v0.2.1

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) MenuPresentation added in v0.8.0

func (_handle *Context) MenuPresentation() MenuPresentation

MenuPresentation returns how the window shows its popup menus (SetMenuPresentation).

func (*Context) Modifiers added in v0.2.17

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 added in v0.3.0

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

OnShortcut declares a handler in the current context's parent scope: the window's, as OnWindowShortcut, at the root, else the parent element's focus subtree, as Element.OnShortcut.

func (*Context) OnWindowShortcut added in v0.8.0

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

OnWindowShortcut declares a handler of the window's shortcut mods+key, which runs when c.Shortcut would report it, wherever c is in the tree: a component built deep in the view hears its keys while the focus is anywhere else, or nowhere, as one built at the root does. Elements around the focus that take the key, and overlays, still come first; one built in a dialog fires while the dialog shows, and one built behind it waits, as Shortcut does.

func (*Context) OpenURL added in v0.2.4

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 added in v0.2.14

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 added in v0.2.5

func (_handle *Context) Preferences() Preferences

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

func (*Context) ReadClipboard added in v0.2.4

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. WriteClipboardThen tells whether the text got there.

func (*Context) Region added in v0.5.0

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

Region returns the user's regional formats (mygo.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 added in v0.3.0

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 added in v0.5.0

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 added in v0.3.0

func (c *Context) Services() Services

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

func (*Context) SetMenuPresentation added in v0.8.0

func (_handle *Context) SetMenuPresentation(p MenuPresentation)

SetMenuPresentation sets how the window shows its popup menus: those of ContextMenu and Menu, the menus MyGo's widgets build with them, as a table's header and cell menus, and the editing menu of text inputs and selectable text. With PopoverMenus they draw in the window as PopoverMenu draws its menu, with its keys, focus and roles, so that an app with a look of its own shows no menu of the desktop's beside its own; with SystemMenus, the default, the system shows them. It stays until set again. PopoverMenu and PopoverMenuButton draw theirs in the window whatever it is. Only the menus MyGo builds follow it: the menu bar, the tray's menu and the Dock's stay the system's, and a web view's are the web view's own.

c.SetMenuPresentation(ui.PopoverMenus)

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. Inside the children of a Themed, which keep its theme, t is for the root and the widgets after the Themed.

func (*Context) SetZoom added in v0.7.0

func (_handle *Context) SetZoom(z float32)

SetZoom zooms the window's content by z, as a browser zooms a page: the view is laid out in a window 1/z its size and shown z times larger, drawn at the screen's resolution times z, so that text, icons, vectors and images stay as sharp as at that size natively, not a picture of the window scaled up. 1 shows the content at its size; the zoom stays until set again, and is clamped to between 0.25 and 5. A frame that sets another builds again at the new size before it shows.

What the view sees is zoomed: Size, TitleBar, Bounds and every length are in the content's DIPs, z of them to the window's. The pointer, text input, input methods, accessibility, context menus, drags and web views follow it. The window's own sizes are not zoomed: Window.SetContentSize and Window.ContentSize are in the window's DIPs, z times the content's.

c.SetZoom(app.zoom) // 1.25 for 125%

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) ShortcutRepeated added in v0.8.0

func (_handle *Context) ShortcutRepeated() bool

ShortcutRepeated reports whether the key that the last Shortcut to report one took came as the auto-repeat of a key held down, as the web's KeyboardEvent.repeat: Context's, an Element's, a list's or an overlay's, and those that run OnShortcut's actions, which can ask it as they run. An action that steps while the key is held takes every key; a toggle takes the press alone, and lets the repeats go by:

if c.Shortcut(0, ui.KeyT) && !c.ShortcutRepeated() {
	app.panel = !app.panel
}

It is false in a frame no shortcut took a key in yet.

func (*Context) Size

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

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

func (*Context) TextSystem added in v0.9.1

func (c *Context) TextSystem() *text.System

TextSystem returns the window's text system: the shared one, unless the window is a Tester's, whose own system keeps its shaping and its glyph atlases apart from the other windows' (#1722). Drawings shape text for Painter.Glyphs in the system they draw with.

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. While the children of a Themed build, it is the Themed's theme.

func (*Context) TitleBar

func (_handle *Context) TitleBar() TitleBar

TitleBar returns the room the window controls take in a window with a hidden title bar (mygo.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()

A sidebar under the controls starts below Bottom:

ui.Column(c).Padding(bar.Bottom+8, 0, 0, 0)

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 added in v0.2.5

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 added in v0.3.0

func (c *Context) Valid() bool

Valid reports whether this context is building a view.

func (*Context) Vibrancy added in v0.3.4

func (_handle *Context) Vibrancy() bool

Vibrancy reports whether the window shows its material (mygo.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) WindowActive added in v0.8.0

func (_handle *Context) WindowActive() bool

WindowActive reports whether the window is drawn as active: the window the user's input goes to, as native apps draw it, while it or one of its flyouts has the keyboard (and always as Window.SetActiveAppearance keeps it). The built-in widgets fade their accent to gray in a window that is not, as AppKit's do (Theme.InactiveAccent), and macOS fades the window's material. A frame that reads it is drawn again as it changes; draw what shows which window has the user's input in a view of your own with it:

icon := c.Theme().Accent
if !c.WindowActive() {
	icon = c.Theme().TextMuted
}

func (*Context) WindowHidden added in v0.8.0

func (_handle *Context) WindowHidden() bool

WindowHidden reports whether nothing of the window shows on screen, as the web's document.hidden: it is minimized, hidden, on another space or desktop, or covered by other windows, as far as the system tells (see the platform differences). A view that shows a clock, a price or what plays stops working while it is hidden, and refreshes as it shows again: the view builds once as it hides, and again as it shows, from the first time it asks. Frames that only move what shows wait while it is hidden anyway.

app.ticker.SetPaused(c.WindowHidden())

func (*Context) WriteClipboard added in v0.2.4

func (_handle *Context) WriteClipboard(s string)

func (*Context) WriteClipboardThen added in v0.8.0

func (_handle *Context) WriteClipboardThen(s string, done func(err error))

WriteClipboardThen puts text on the clipboard as WriteClipboard does, and done, unless nil, gets what came of it a moment later, before a frame builds anew with what it changed, as navigator.clipboard's writeText resolves or rejects: an error when the text did not get there, as when another app holds the clipboard, or a browser refuses a write the user did not act for (a press or a key, a moment before). A copy button shows "Copied" or "Failed" with it:

if ui.Button(c, "Copy").Clicked() {
	c.WriteClipboardThen(link, func(err error) {
		app.copied, app.copyFailed = err == nil, err != nil
	})
}

func (*Context) Zoom added in v0.7.0

func (_handle *Context) Zoom() float32

Zoom returns the zoom SetZoom set, 1 for none.

type Current added in v0.8.0

type Current uint8

Current is the item an element is the current one of, among those around it (Element.Current), as ARIA's aria-current says.

const (
	// CurrentNone is not current.
	CurrentNone Current = iota
	// CurrentItem is the current item of a set, aria-current="true".
	CurrentItem
	// CurrentPage is the page the user is on: the last crumb of a
	// breadcrumb trail, or the link of a navigation bar to the page shown.
	CurrentPage
	// CurrentStep is the step of a process the user is at, as in a
	// wizard's steps.
	CurrentStep
	// CurrentLocation is the place shown, as in a flow chart or a map.
	CurrentLocation
	// CurrentDate is today in a calendar, and CurrentTime now in a
	// timetable.
	CurrentDate
	CurrentTime
)

type Cursor

type Cursor uint8

Cursor is a pointer shape.

type Direction added in v0.5.0

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 mygo 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 added in v0.5.0

func (d Direction) String() string

type DraggableOptions added in v0.4.5

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 added in v0.2.1

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 added in v0.2.1

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 added in v0.4.3

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 added in v0.5.3

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 added in v0.5.4

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 navigation landmark, which Label names, and the last item as the current page.

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 added in v0.2.5

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. Browse makes the keys and the buttons move without choosing.

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 added in v0.2.5

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 CheckboxState added in v0.8.0

func CheckboxState(c *Context, state *CheckState, label string) Element

CheckboxState creates a check box that can be mixed, with a label: a click, or Space while it has the focus, checks it, or unchecks it when it is checked, setting *state, and Changed reports a click. It shows a dash while mixed, and assistive technology sees it mixed. CheckboxGroup is one over the check boxes it holds.

func CheckboxStateBase added in v0.8.0

func CheckboxStateBase(c *Context, state *CheckState) Element

CheckboxStateBase creates a check box without a look that can be mixed, as a "select all" box in a table's header, checked when every row is and mixed when some are: a row that sets *state to CheckOn when clicked, or with Space while it has the focus, or to CheckOff when it is CheckOn, which Changed reports, and that assistive technology sees as a check box, checked, unchecked or mixed. Draw its box from *state; CheckboxState is CheckboxStateBase with the theme's look.

all := ui.CheckOff
switch n := app.selectedCount(); {
case n == len(app.rows):
	all = ui.CheckOn
case n > 0:
	all = ui.CheckMixed
}
cb := ui.CheckboxStateBase(c, &all).Label("Select all")
cb.Children(func() { app.box(c, all) }) // a dash while mixed
if cb.Changed() {
	app.selectAll(all == ui.CheckOn)
}

func Collapsible added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 DecimalInput added in v0.7.4

func DecimalInput(c *Context, value *string, lo string, hi string, step string) Element

DecimalInput creates a text input editing *value as an exact decimal between lo and hi, which the arrows Up and Down, and the buttons beside it, step by step: a NumberInput for amounts of money, which it never rounds. *value is written with exactly the decimals of step, as "1234.50"; lo and hi are written the same way, "" for no limit. What is typed applies as soon as it is a number in range, with '.' before its decimals and ',' between groups of three digits: "1,234.5" sets "1234.50", and shows so once the input loses the focus. Text with more decimals than step's (other than zeros), out of range or not a number leaves *value as it was and marks the input with Error, whose message an enclosing Field shows, until it is corrected. A value the app sets replaces what was typed. Changed reports a new value.

ui.DecimalInput(c, &app.amount, "0", "", "0.01")

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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

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

func Grid added in v0.2.1

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 added in v0.2.5

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
		}
	}
})

PopoverMenuButton draws its menu in the window, with the theme's look.

func Meter added in v0.2.5

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, or the levels' own colors. Background colors its track. 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 NativeView added in v0.8.2

func NativeView(c *Context, v PlatformView) Element

NativeView shows a view of the platform, a value of a native module's interface that embeds native.View (an NSView on macOS), in the element's content box, as WebView shows a web view: it has no size of its own and takes its size from layout, it is cut to the element's Radius, and what paints after it shows over it, its children first. Make the view once, outside the view function, and show it from there:

ui.NativeView(c, app.player).Fill().Children(func() {
	ui.Text(c, caption).Absolute().Left(24).Bottom(24)
})

The view takes the pointer where it shows, and the keyboard once clicked or tabbed into, as any view of the platform. A view the frame does not build hides and keeps its state; one closed leaves the window. Where views of the platform cannot show, as in browsers, the element shows nothing.

v is nil where the module has no implementation, its constructor having returned errors.ErrUnsupported: the element is then a plain box, which paints its background and children, so a view can show something else in the view's place.

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 added in v0.2.5

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. It walks the open items in every frame, unless s.Generation tells it when children changes, which keeps trees of any size 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 added in v0.2.5

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 PopoverMenuButton added in v0.7.3

func PopoverMenuButton(c *Context, label string, build func(m *Menu), options ...PopoverMenuButtonOptions) Element

PopoverMenuButton creates a button showing label and an arrow, as MenuButton does, whose menu MyGo draws in the window with the theme's look, as PopoverMenu draws a context menu (Element.PopoverMenuButton):

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

Its options place the menu and open it from the app, as Element.PopoverMenuButton's do.

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. It fills in the accent color, or the color TextColor gives it, as a quota bar in a product's own color, over a track in the theme's Border color, or the one Background gives it.

ui.Progress(c, app.used/app.quota).TextColor(brand).Label("Storage")

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.1

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 added in v0.2.5

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, or what Placeholder sets, 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 added in v0.2.5

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. Its segments are as wide as their labels; FillEqually makes it as wide as its parent, its segments sharing the width.

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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. SplitReset makes a double click on the divider put first back at a size the app chooses.

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

func SplitPercent added in v0.5.5

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 added in v0.5.5

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

SplitVerticalPercent is SplitPercent with first above second.

func StepSlider added in v0.2.5

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 added in v0.2.5

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; Changed reports the new layout once the user lets go, or once a double click fits a column to its cells, for the app to save. 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 added in v0.2.17

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 added in v0.2.17

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 added in v0.2.17

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 added in v0.2.17

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 Themed added in v0.7.4

func Themed(c *Context, t *Theme) Element

Themed creates a column whose children build with t, as SetTheme has the whole window build: the widgets inside take their colors and metrics (Spacing, Radius, FontSize) from t, Context.Theme returns t while they build and Painter.Theme while they paint, and the popovers, menus, tooltips and dialogs they open take t too. The column paints t's Background, and the text inside takes t's Text color, FontSize and Font, as the root has the window's theme's; Background(ui.Transparent) keeps what is behind it instead. The root, and what is built after the column, keep the window's theme. Light beside dark, as a theme picker previews them:

ui.Row(c).Fill().AlignItems(ui.Stretch).Children(func() {
	for _, t := range []*ui.Theme{ui.LightTheme(), ui.DarkTheme()} {
		ui.Themed(c, t).Grow(1).Padding(16).Gap(8).Children(func() {
			ui.Text(c, "Preview")
			ui.Button(c, "OK")
		})
	}
})

A nil t makes it a Column.

func TimeInput added in v0.2.5

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 added in v0.2.15

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 or the keyboard focus is in it with the window's, and runs on while 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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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. Query binds what is being typed, for suggestions the app looks up and matches itself as the user types.

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

func Toolbar added in v0.2.5

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 added in v0.2.15

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; the theme's TooltipDelay changes both. It goes as the pointer leaves anchor or presses it, as a menu or popover of anchor opens, and with Escape, until the pointer comes back or the focus does; it does not show while that menu or popover shows. 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, Home and End to the first and the last, Right opens the item or moves to its first child, Left closes it or moves to its parent, and typing the first letters of an item moves to it. The tree is one stop of Tab.

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)
})

Tree is TreeBase with the theme's look.

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 Video added in v0.7.2

func Video(c *Context, p *VideoPlayer) Element

Video creates an element showing a player's video, by default at its size as DIPs, scaled to fit when given another size, as Image shows a bitmap:

//go:embed waves.gif
var wavesGIF []byte

d, err := ui.NewGIFDecoder(wavesGIF)
...
app.waves, err = ui.NewVideoPlayer(d)
app.waves.SetLoop(true)

ui.Video(c, app.waves).Fill().Fit(ui.Cover)

The video moves on only while the view builds it and some of the window shows: one that went out of the view, or a window out of sight, goes on from where it stood; a system's video with sound plays on, unseen, as a browser's does. Each frame of the video is a frame of the window, which After asks for as it comes due. While the desktop asks for less motion (Preferences.ReduceMotion), a decoder's video, and a system's muted one, shows its first frame and does not play.

func WebView added in v0.4.0

func WebView(c *Context, v NativeWebView) Element

WebView shows a web view, made with mygo.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 (mygo.WebView.Focus) or tabbed into: Tab stops at the element. The keys the page leaves unhandled come to the native UI as if the element had the focus, which the shortcuts around it and the window's see. 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 added in v0.4.8

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. The elements inside a text field described so show to assistive technology too, as those of other text fields do not.

func (Element) AccessChildren added in v0.9.1

func (_handle Element) AccessChildren(fn func(parent *platform.AccessNode, add func(arg0 platform.AccessNode))) Element

AccessChildren has fn add nodes of its own inside the element's, after Access's fn described it and before the elements inside it, only while assistive technology reads the window: what stands for parts of the element that are no elements, as the lines a diff viewer shows, each read as added or deleted. fn reads the element's node, parent, and adds each node with add, whose Parent it sets; their IDs must be no element's, and the same for the same part from frame to frame. Actions on them do nothing. As Access, it takes the module's internal type.

func (Element) AccessDisabled added in v0.8.0

func (_handle Element) AccessDisabled(off bool) Element

AccessDisabled tells assistive technology that the element and those inside it are unavailable when off is true, as HTML's aria-disabled does, while they keep the keyboard focus, their place in the Tab order, the pointer and their look: a screen reader still reaches them and reads them, as dimmed or unavailable, with their Description, which can say why. It is for what the user must still find while it cannot be used, as a menu item whose action is blocked, a tab disabled but still in the arrows' order, or a submit button while the form is not valid:

del := ui.Button(c, "Delete project").AccessDisabled(app.locked)
if app.locked {
	del.Description("Unlock the project to delete it")
}
if del.Clicked() && !app.locked {
	app.deleteProject()
}

It only tells: clicks and keys still reach the element, which the view ignores while it is unavailable, and it does not dim it, which the view styles itself if it wants. Assistive technology focuses it, but neither presses nor edits it. Disabled does all of it at once: no clicks, no focus, and half the opacity.

func (Element) AccessHidden added in v0.8.0

func (_handle Element) AccessHidden(hide bool) Element

AccessHidden leaves the element and those inside it out of what assistive technology reads when hide is true, while they still show, as HTML's aria-hidden does: none of them is in its tree, their text names no element around them, and it can neither press, focus nor edit them. The pointer and the keyboard still reach them, unless they IgnoreInput too, which makes them inert, as HTML's inert does; without it, keep the keyboard focus out of them, where assistive technology cannot follow.

What shows but is not there to read is so read once, or not at all: a page sliding out beside the one that replaces it, the cards peeking from behind the front one of a stack, a copy of a text fading into another:

if app.leaving >= 0 {
	page(c, app.leaving).Absolute().Translate(-x, 0).IgnoreInput(true).AccessHidden(true)
}
page(c, app.tab).Translate(width-x, 0)

RoleNone leaves out the element but not those inside it.

func (Element) AccessSelected added in v0.8.0

func (_handle Element) AccessSelected(on bool) Element

AccessSelected tells assistive technology whether the element, a tab, an option, a row, a cell or an item of a tree of your own, is selected, as ARIA's aria-selected, without the accent background and text color Selected paints: for one that shows its choice its own way, as a tab underlined or a row with a check mark.

tab := ui.ButtonBase(c).Role(ui.RoleTab).Label(name).AccessSelected(i == app.tab)
if i == app.tab {
	tab.Bold()
}

It sets the state Selected sets, which Checked also sets on these roles, so every platform reads it as Selected's: a row or a cell saying whether it is selected, false or true, is one its table or grid chooses among others (Selectable). It only tells: the view shows the choice, and changes it as the element is clicked.

func (Element) ActiveDescendant added in v0.2.13

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 added in v0.2.1

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 added in v0.4.3

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, in sRGB or, with a's Oklab, in Oklab; 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 added in v0.4.3

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. 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)

It starts at the first pose: an element that the frame before did not pose, as one built for the first time, shows at p at once, and moves only when a later frame poses it elsewhere. To come in from a pose, as a flyout's panel rising as it shows, pose the element there in one build, ask for another frame (Context.Invalidate), and pose it at its place in the next:

entered := ui.Local(panel, "entered", func() bool { return false })
p := ui.Pose{}
if !*entered {
	p, *entered = ui.Pose{Y: 8, Fade: 1}, true
	c.Invalidate()
}
panel.AnimatePose(p, ui.Snappy)

An element appearing in a parent that the frame before showed comes in with the Enter of its Transition too.

func (Element) AnimateTo added in v0.4.3

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, unless a's NonMotion says it moves nothing, as a fade:

op := e.AnimateTo("fade", target, ui.Animation{Duration: 200 * time.Millisecond, NonMotion: true})

func (Element) AnimateWith added in v0.2.1

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 added in v0.4.3

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 added in v0.2.8

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) AttachEdgeMargin added in v0.8.0

func (_handle Element) AttachEdgeMargin(v float32) Element

AttachEdgeMargin sets how far an element placed with AttachTo stays from the window's edges, v DIPs on each side, where it is 4 unless set: a panel that must not touch the edges of a small window keeps 12 from them, as the inset-modified containing block of CSS Anchor Positioning keeps a positioned box inside the insets given to it. It is the room the element flips and moves to stay in, and that one scrolling is limited to.

func (Element) AttachTo added in v0.2.13

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. AttachedAnchors tells the side it went to.

func (Element) AttachedAnchors added in v0.8.0

func (_handle Element) AttachedAnchors() (Anchor, Anchor)

AttachedAnchors returns the points of its target's box and of its own that AttachTo put together as the layout placed the element: those asked for, or, where it went to the other side of target or the other way along it to stay in the window, those across or down from them, as Floating UI's placement: AnchorTop and AnchorBottom for a panel asked below its button, with AttachTo(button, ui.AnchorBottom, ui.AnchorTop), that went above it. Start and end anchors stay start and end ones. The view reads the last frame's, which are those asked for until the element is laid out, as in the frame it first shows; Draw reads this frame's. From that first frame, AttachedOrigin puts the element's transform origin on its own point, and a Motion's Flip mirrors its Enter and Exit, on the side the layout chose. An element not attached to another returns its Attach anchors, or AnchorTopLeft twice without them.

func (Element) AttachedOrigin added in v0.8.0

func (_handle Element) AttachedOrigin() Element

AttachedOrigin sets the transform origin on the element's own point that AttachTo puts on its target, on whichever side of it the layout puts the element (AttachedAnchors), from the frame it shows: a tooltip or a menu scaling in, or out, grows from the edge nearest its trigger, as Radix's popper transform origin. It replaces TransformOrigin on an element attached to another.

func (Element) AutoComplete added in v0.8.0

func (_handle Element) AutoComplete(kind AutoComplete) Element

AutoComplete tells assistive technology what the suggestions of a text input or a combobox of your own complete as the user types, as ARIA's aria-autocomplete: AutoCompleteList for a popup of the values matching what was typed, which screen readers announce with the field so that the user knows to look there, AutoCompleteInline for the text completed in place. It only tells it: the view shows the suggestions itself, as in ComboboxBase's popup. Combobox, Autocomplete, and a TokenField with suggestions or a Query, tell AutoCompleteList themselves; AutoCompleteNone takes it back.

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 added in v0.4.3

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) Balance added in v0.8.0

func (_handle Element) Balance() Element

Balance wraps the element's text in lines of about the same length, as CSS's text-wrap: balance does: a heading or a short callout that takes two lines takes two of half its length each, rather than a full line and a word alone on the next. The text takes as many lines as it would without it, at the width layout gives it, and keeps its alignment within that width. Each paragraph is balanced on its own, once a layout, as the text system keeps it.

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 added in v0.2.1

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 added in v0.3.0

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

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

func (Element) Blur added in v0.5.5

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 added in v0.2.1

func (_handle Element) BorderColor(c Color) Element

BorderColor sets the color of the border.

func (Element) BorderConicGradient added in v0.5.5

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 added in v0.5.0

func (_handle Element) BorderEndWidth(v float32) Element

func (Element) BorderLinearGradient added in v0.5.5

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 added in v0.5.0

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 added in v0.2.1

func (_handle Element) BorderStyle(s BorderStyle) Element

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

func (Element) BorderWidth added in v0.2.1

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 added in v0.2.1

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, the content's when zoomed (Context.SetZoom); it is empty for an element the previous frame lacked. LayoutBounds returns its box before visual transforms.

func (Element) Browse added in v0.7.4

func (_handle Element) Browse() Element

Browse lets the user move about a Calendar without choosing a day: its buttons and Page Up and Page Down only show other months, and the arrows, Home and End only move among the days, until a click, Enter or Space chooses one, as in a date input's calendar. Changed then reports only a day chosen, as a calendar in a popover that closes when the user picks a day needs. The calendar goes back to *date as the app sets another.

func (Element) Busy added in v0.8.0

func (_handle Element) Busy(on bool) Element

Busy tells assistive technology whether the element's content is about to change, as a region loading, or one updated in several steps: screen readers wait until it is no longer busy to read what changed in it. A placeholder standing in for the content, as a skeleton or a spinner, says what is happening (a RoleStatus labelled "Loading").

func (Element) Cache added in v0.7.0

func (_handle Element) Cache() Element

Cache keeps what the element paints, with its children, in a bitmap of the GPU that frames draw as one image, as Flutter's RepaintBoundary and SwiftUI's drawingGroup do: for a still subtree that costs much to draw, as a card of gradients, blurred images and large shadows, under or around a drawing that moves. A frame redrawing where something above or next to it changed then draws the bitmap there, not each of its layers, and moving or rotating the element (Translate, Rotate, AnimatePose) moves the bitmap, not what it holds.

The bitmap holds the element's box, and what it and those inside it paint around it: shadows, focus rings, and children beyond the box that it does not clip, as Draw callbacks paint (within the box and the shadows' reach), in the pixels it shows on: at the window's scale times the scale the element's transform draws it at (Scale, AnimatePose, Transition's ScaleContent), so that scaled up it is as sharp as the subtree laid out larger. At rest it is drawn at that scale itself, on whole pixels where the transform only scales and moves it; while the scale changes, as an animation grows it, at steps of about 9% (at or above the scale), drawn again only as the scale crosses one, and once more at the scale itself in the frame after it stops. It is drawn again, too, when what the subtree paints changes: built anew with other content, laid out at another size, at another window scale or in another theme, or as something inside it moves on its own (Painter.AnimationFrame, a pose, a transition), as then it is every frame. Painting the window still paints the subtree, to tell; frames that only paint the drawings that asked for them (Painter.AnimationFrame, Painter.After) do not.

As in an effect's bitmap (Effect), its text is smoothed in grayscale where the subtree paints no opaque background under it, web views inside it do not show, and a subtree larger than 8192 pixels across is drawn as it is. A bitmap drawn larger than the window's scale is at most 4096 pixels across, and 8 times the window's scale: beyond, it is stretched as before. Turned, skewed or in perspective, the bitmap is resampled, and shows a little softer than the shapes it holds would.

func (Element) CaretColor added in v0.8.0

func (_handle Element) CaretColor(c Color) Element

CaretColor sets the color of the insertion caret of the text inputs in the element, as CSS's caret-color does, a field's own text color for one; the theme's accent is the color elsewhere.

func (Element) CaretWidth added in v0.7.4

func (_handle Element) CaretWidth(width float32) Element

CaretWidth sets this input's painted caret width in DIPs for this build. It defaults to one DIP. Positive widths are rounded to device pixels, at least one pixel wide; zero and negative widths hide the caret. It does not change text layout, input-method candidate bounds or caret blinking. Other elements are unaffected.

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 added in v0.2.13

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, or whether an option (RoleOption) is selected. Bases set it from their value.

func (Element) ChildExit added in v0.8.0

func (_handle Element) ChildExit(m Motion) Element

ChildExit says where the children of the element that leave in this frame go, in place of the Exit of their Transitions: those whose Transition has an Exit, which are copied as they go. It suits an exit decided as they leave, as a calendar, a wizard or a carousel stepping forward or back, whose page going goes the way of the step that sent it, even when the step turned around in the frame it went:

dir := float32(app.dir) // 1 forward, -1 back
ui.Box(c).Fill().ChildExit(ui.Motion{X: -40 * dir}).Children(func() {
	ui.Column(c.Key(app.page)).Absolute().Fill().Transition(ui.ElementTransition{
		Enter: &ui.Motion{X: 40 * dir},
		Exit:  &ui.Motion{X: -40 * dir},
	})
})

Copies already on their way go on as they went.

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 added in v0.2.5

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) ClipInset added in v0.8.0

func (_handle Element) ClipInset(top float32, right float32, bottom float32, left float32, radius float32) Element

ClipInset clips the element and what is inside it, its background, shadows, border and children, to its box inset by top, right, bottom and left DIPs, with corners rounded by radius, as CSS's clip-path: inset() does. A negative inset reaches beyond the box on that side, as a clip along one axis that leaves a shadow whole along the other. The insets may change every frame, as values an element animates do:

hidden := float32(100)
if app.open {
	hidden = 0
}
card.ClipInsetPercent(0, card.AnimateTo("wipe", hidden, ui.Smooth), 0, 0, 0)

What the clip hides takes no clicks.

func (Element) ClipInsetPercent added in v0.8.0

func (_handle Element) ClipInsetPercent(top float32, right float32, bottom float32, left float32, radius float32) Element

ClipInsetPercent is ClipInset with insets in percent of the box: top and bottom of its height, right and left of its width, as CSS's inset() takes percentages. An inset going from 100 to 0 wipes the element in from the other side.

func (Element) ClipX added in v0.2.1

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 added in v0.2.1

func (_handle Element) ClipY() Element

func (Element) Column

func (_handle Element) Column() Element

Column lays the children out from top to bottom.

func (Element) ColumnCount added in v0.8.0

func (_handle Element) ColumnCount(n int) Element

ColumnCount tells assistive technology how many columns a table, grid or tree grid of your own has, built or not (aria-colcount).

func (Element) ColumnIndex added in v0.8.0

func (_handle Element) ColumnIndex(i int) Element

ColumnIndex tells assistive technology the place of a cell or a column header among all the columns of its table, grid or tree grid, from 1 (aria-colindex): for one that builds only the columns in view, or leaves some out. Cells without one follow the one before them, after the columns it covers (ColumnSpan).

func (Element) ColumnSpan added in v0.2.1

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. A cell of a table or a grid (RoleCell, RoleColumnHeader, RoleRowHeader) tells assistive technology it covers them, as ARIA's aria-colspan, whether or not its row lays it out in a grid: screen readers read a cell covering two columns as one.

func (Element) ColumnStart added in v0.2.1

func (_handle Element) ColumnStart(n int) Element

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

func (Element) ColumnTracks added in v0.2.1

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 added in v0.2.1

func (_handle Element) Columns(n int) Element

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

func (Element) Composing added in v0.2.13

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 added in v0.5.5

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 added in v0.4.3

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; in a list, while the list has the focus and the element's row is chosen. 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()
})

PopoverMenu draws the same menu in the window, with the theme's look, as ContextMenu does while the window draws its menus (SetMenuPresentation).

func (Element) Controls added in v0.8.0

func (_handle Element) Controls(target Element) Element

Controls tells assistive technology that the element controls the content or the presence of target, as ARIA's aria-controls: the region a disclosure button opens, or the list a filter's input narrows. Screen readers offer to move to it. Call it once target is built, once for each element it controls.

func (Element) CopyData added in v0.5.0

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) Current added in v0.8.0

func (_handle Element) Current(kind Current) Element

Current tells assistive technology that the element is the current one of the items around it, as the page the user is on in a breadcrumb trail or a navigation bar, which screen readers read with it ("current page"). CurrentNone takes it back.

func (Element) Cursor

func (_handle Element) Cursor(c Cursor) Element

Cursor sets the pointer's shape over the element.

func (Element) Debug added in v0.2.1

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 added in v0.2.1

func (_handle Element) DecorationColor(c Color) Element

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

func (Element) DecorationThickness added in v0.2.1

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) DescribedBy added in v0.8.0

func (_handle Element) DescribedBy(desc Element) Element

DescribedBy has desc, an element the view draws, as a hint below a field or a help text beside it, describe the element to assistive technology, as ARIA's aria-describedby does: screen readers read desc's text after the element's name and value, as a Description, which it follows. The text is desc's Label, else the texts inside it, as a sentence with a link in it, read as one; it counts even when desc is hidden from assistive technology (AccessHidden). Call it once both are built, before or after the element, once for each element describing it, in the order to read them. On a Field, it describes the field's control.

hint := ui.Text(c, "16 digits, no spaces").TextColor(t.TextMuted)
ui.TextInput(c, &app.card).Label("Card number").DescribedBy(hint)

func (Element) Description added in v0.2.5

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) DimDisabled added in v0.8.0

func (_handle Element) DimDisabled(dim bool) Element

DimDisabled sets whether the element shows at half its opacity, with what is inside it, while Disabled disables it, as it does by default, bases too; an element disabled by one around it dims with that one. A widget of your own that shows being disabled in a look of its own, as a card that keeps the reason it is unavailable readable, turns it off and styles itself while IsDisabled.

func (Element) Direction added in v0.5.0

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 show at half their opacity, unless DimDisabled turns that off. AccessDisabled keeps their clicks and their focus, for what assistive technology must still reach.

func (Element) Dismissed added in v0.4.0

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 added in v0.2.8

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) DottedUnderline added in v0.7.4

func (_handle Element) DottedUnderline() Element

DottedUnderline underlines text with a line of dots, as links mark hover.

func (Element) DoubleClicked

func (_handle Element) DoubleClicked() bool

DoubleClicked reports a double click on the element.

func (Element) Drag added in v0.2.5

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 added in v0.2.17

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 added in v0.2.17

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 added in v0.4.3

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

DragEnded reports whether the pointer pressing the element with the primary button, 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, nor does a drag with another button, nor a press the system canceled (PressCanceled).

func (Element) DragMissed added in v0.8.0

func (_handle Element) DragMissed() (Point, bool)

DragMissed reports, in the frame after, that the value the element drags (Drag) was let go over no element taking it, and where, in the window's coordinates: outside the window when it was let go past its edge, as to tear a tab out into a window of its own. A drag given up, with Escape, is not missed.

func (Element) DragOffset added in v0.4.5

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 added in v0.4.3

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 with the primary button (Dragged).

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 added in v0.4.5

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. A press the system cancels (PressCanceled) throws nothing, and the element goes back to where the press took it. 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 with the primary button, as Pressed: a drag with another button moves nothing (PressedButton). The moves just before the pointer let go come while the element is still pressed, and the press ends in the build after.

func (Element) Dragging added in v0.2.5

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) DrawObjects added in v0.7.0

func (_handle Element) DrawObjects(fn func(p *Painter, at int, r Rect)) Element

DrawObjects paints the inline objects of a text (Span.ObjectWidth) with p, after its glyphs: fn gets each one that shows, its rune in the text, the text elements' inside it included, and its box, in window DIPs, ObjectHeight above the baseline and ObjectDescent below. It paints in the text's clip and in the transform of the element holding the object. fn only paints: it may run more than once a frame.

ui.RichText(c, ui.Span{Text: "area "}, ui.Span{Text: "\uFFFC", ObjectWidth: w, ObjectHeight: h, ObjectDescent: d}).
	DrawObjects(func(p *ui.Painter, at int, r ui.Rect) { formula.Draw(p, r) })

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 added in v0.5.3

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 added in v0.2.1

func (_handle Element) Ellipsis(s string) Element

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

func (Element) End added in v0.5.0

func (_handle Element) End(v float32) Element

func (Element) EndPercent added in v0.5.0

func (_handle Element) EndPercent(p float32) Element

func (Element) Error added in v0.2.5

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) ErrorMessage added in v0.8.0

func (_handle Element) ErrorMessage(msg Element) Element

ErrorMessage has msg, an element the view draws holding the message of the element's error, tell assistive technology why its value is not valid, as ARIA's aria-errormessage does: while the element is invalid (Invalid, Error), screen readers read msg's text with it, first in its description, and those that follow the relation go to msg. While it is valid, msg says nothing of it, so the view may keep msg built, empty or hidden. Call it once both are built, once for each element holding a message. On a Field, it is the field's control's message.

in := ui.TextInput(c, &app.email).Label("Email").Invalid(app.emailError != "")
if app.emailError != "" {
	in.ErrorMessage(ui.Text(c, app.emailError).TextColor(t.Danger))
}

func (Element) Expanded added in v0.2.13

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) FillEqually added in v0.9.0

func (_handle Element) FillEqually() Element

FillEqually makes a Segmented or a ToggleGroup as wide as its parent's content, as FillWidth does, and shares that width equally among its segments, as AppKit's fillEqually distribution: the one chosen takes its share, its label in the middle, and a label longer than its share ends with an ellipsis. The segments look and behave as they do otherwise, disabled ones too. Call it on SegmentedBase's Track after building its segments; on other elements it is FillWidth. A width set after it sets the control's, which its segments share still.

ui.Segmented(c, &app.theme, "Light", "Dark", "System").FillEqually().Label("Appearance")

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 added in v0.2.1

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(options ...FocusOptions) Element

Focus gives the element the keyboard focus. Called in every frame, it keeps it there; AutoFocus gives it once. A field around an input, as SearchField's, gives it to its input, where typing goes. When the focus moves to it, it scrolls the containers around it as little as shows it, as Tab does and the web's focus() does; ScrollIntoView lines it up otherwise. While a pointer button is held it scrolls nothing: what a press focuses, as the line a grip moves, is under the pointer.

Its options, as the web's focus() options, keep the scroll where the user left it: the focus returned to a cell of a grid when a dialog closes, without scrolling the grid.

cell.Focus(ui.FocusOptions{PreventScroll: true})

func (Element) FocusBind added in v0.3.0

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 added in v0.2.5

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; in a radio group or a tab list, the one chosen 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) FocusLeft added in v0.8.0

func (_handle Element) FocusLeft() bool

FocusLeft reports whether the keyboard focus left the element since the last frame: it was on the element or inside it, and is now outside it, or nowhere, as the window lost the keyboard. That is the web's focusout whose relatedTarget the element does not contain. The overlays attached to the element and to those inside it (AttachTo), as a combobox's list or a button's popover, count as inside it, as does the element it is attached to, as PressedOutside has them: a combobox closes as the focus leaves its field, but not as it moves into its list.

field := ui.TextInput(c, &app.query)
if field.FocusLeft() {
	app.open = false
}

Where the focus went is what the elements tell as they are built (Focused, FocusWithin), and a Handle's FocusWithin before its control is.

func (Element) FocusRing

func (_handle Element) FocusRing(show bool) Element

FocusRing sets whether MyGo 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) FocusRingColor added in v0.8.0

func (_handle Element) FocusRingColor(color Color) Element

FocusRingColor sets the color of the element's focus ring, in place of the theme's Focus, as for an element on a background the theme's ring does not stand out on.

func (Element) FocusRingOffset added in v0.8.0

func (_handle Element) FocusRingOffset(d float32) Element

FocusRingOffset sets how far outside the element's edge its focus ring goes, in DIPs, in place of the theme's FocusRingOffset: 0 puts it on the edge, and a negative offset inside it, as for an element whose ancestor clips what goes past it, as a header in an accordion's box. Its corners follow the element's, as CSS's outline does. The widgets that ring a part of themselves, as a check box its box, ring it so.

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: for a field around an input, as SearchField's, whether its input has it.

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 added in v0.2.1

func (_handle Element) GapX(v float32) Element

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

func (Element) GapY added in v0.2.1

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 added in v0.2.1

func (_handle Element) Grayscale() Element

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

func (Element) Grid added in v0.2.1

func (_handle Element) Grid() Element

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

func (Element) GridRows added in v0.3.0

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 added in v0.2.4

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 added in v0.2.17

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) HasPopup added in v0.8.0

func (_handle Element) HasPopup(kind Popup) Element

HasPopup tells assistive technology the kind of popup the element opens, as a button opening a list of options (PopupListBox) or a menu (PopupMenu), which Expanded says shows: screen readers read it with the element ("pop-up button", "menu button") and offer to open it. PopupNone takes it back. Menu buttons (Menu, PopoverMenuButton, MenuButton, MenuBase) tell PopupMenu themselves; HasPopup, before or after, wins over it.

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) Hidden added in v0.7.0

func (_handle Element) Hidden(hide bool) Element

Hidden hides the element and its children when hide is true, as CSS's display: none does: unlike an Invisible element, it takes no room in the layout, nor a gap between its siblings, and draws nothing, takes neither the pointer nor the focus, and is not read by assistive technology. It is still built, so that what is inside it keeps its state (scroll offsets, text being edited, animations) while it is hidden, and shows as it was once hide is false again:

ui.Column(c).Hidden(!app.showDetails).Children(func() { ... })

The focus leaves it as it hides, and what is attached to it (AttachTo) hides with it. A List's rows are built as the list lays out, so a hidden List builds none.

func (Element) Highlighted

func (_handle Element) Highlighted() bool

Highlighted reports whether an option of a select, or an item of a menu (MenuBase), is the one the pointer or the arrows are on.

func (Element) HitTest added in v0.8.0

func (_handle Element) HitTest(fn func(x float32, y float32, r Rect) bool) Element

HitTest sets where in its box the element takes the pointer: where fn reports true for the pointer at (x, y), in the coordinates Draw paints in, r being its box as Draw gets it. Elsewhere the pointer reaches what is under it, as with PassThrough, so that a pie's segment, a map's region or a ring takes a press, the hover and the cursor only where it paints, as SVG's pointer-events: visiblePainted. The elements inside it take the pointer as they would; fn runs as the pointer moves and presses, on the window's thread, and only tests:

ring := func(r ui.Rect) *ui.Path {
	var p ui.Path
	cx, cy := r.X+r.W/2, r.Y+r.H/2
	return p.Circle(cx, cy, r.W/2).Circle(cx, cy, r.W/2-12).FillRule(ui.EvenOdd)
}
ui.Box(c).Size(120, 120).
	Draw(func(p *ui.Painter, r ui.Rect) { p.FillPath(ring(r), accent) }).
	HitTest(func(x, y float32, r ui.Rect) bool { return ring(r).Contains(x, y) }).
	OnClick(func() { … })

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.

Read as the view builds, the pointer coming over the element or leaving it builds the view anew, every element of it; read in a Draw callback, as the window paints, it only paints the last frame's elements again, as the toolkit's controls do for their hovered looks.

func (Element) ID

func (_handle Element) ID() uint64

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

func (Element) IgnoreInput added in v0.7.4

func (_handle Element) IgnoreInput(ignore bool) Element

IgnoreInput makes the element and those inside it ignore the pointer and the keyboard when ignore is true, while they still show and read to assistive technology. The pointer goes through to what is under them, as PassThrough lets it: hovering, pressing, scrolling, dragging and the cursor are those of what is under them. Neither Tab nor a click gives them the focus, and they lose it as they start ignoring input. Assistive technology still finds them, with their roles and names, and presses them, which Clicked reports; it can neither focus them nor move a slider among them with its keys. A WebView inside them still takes the pointer, which the system gives its view.

A control a row shows while it is hovered, as a button deleting it, can stay built and described at rest, without taking a press meant for the row:

row := ui.Row(c).Padding(8)
hovered := row.Hovered()
row.Children(func() {
	ui.Text(c, item.Title).Grow(1)
	del := ui.Button(c, "Delete").IgnoreInput(!hovered)
	if !hovered {
		del.Opacity(0)
	}
	if del.Clicked() {
		removed = item.ID
	}
})

Unlike HTML's inert, it leaves them to assistive technology. Invisible and Hidden hide them from it too, and Disabled takes their press away; AccessHidden hides them from it alone.

func (Element) InView added in v0.4.3

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. When what it answers from changes, as a scroll brings the element in, MyGo builds another frame, so that the view reads the new answer.

func (Element) InViewAmount added in v0.8.0

func (_handle Element) InViewAmount(amount float32, margin ...float32) bool

InViewAmount reports whether at least amount of the element's area, from 0 to 1, showed in the frame before, within the window and the scroll containers and clips around it, grown by margin as InViewMargin grows them: as IntersectionObserver's threshold, and Motion's amount for whileInView and useInView, and builds another frame when what it answers from changes, as InView does. An impression counts once half of a card shows with 0.5, an animation starts at a fifth of it with 0.2, and 1 waits for all of it; 0 is InViewMargin. Its area is that of its box as transforms move it, the box holding them as InView's clips do.

card := ui.Column(c).Key(ad.ID)
if card.InViewAmount(0.5) {
	app.counted(ad.ID)
}

func (Element) InViewMargin added in v0.8.0

func (_handle Element) InViewMargin(margin ...float32) bool

InViewMargin reports whether some of the element showed in the frame before, as InView does, with the window and the scroll containers around it grown by margin, in DIPs, CSS style as Padding: all sides, vertical and horizontal, or top, right, bottom and left. As IntersectionObserver's rootMargin and scrollMargin, a margin of 200 has the element in view once it is within 200 DIPs of showing, to load what it shows before it scrolls in, and a negative one only once it is that far inside; other clips around it clip it as they do. As InView does, it has MyGo build another frame when what it answers from changes.

func (Element) InputMethod added in v0.5.0

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 added in v0.4.0

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) Invalid added in v0.8.0

func (_handle Element) Invalid(on bool) Element

Invalid marks the element's value as not valid, as ARIA's aria-invalid, without a message: assistive technology reads the element as invalid, and a text input draws its border in the theme's Danger color, but its description stays as it is. It suits a required field marked as the user leaves it empty, whose message waits for the form to be submitted, or a control whose message is an element of its own (ErrorMessage). On a Field, it marks the field's control. false leaves the element as it is: valid, unless Error, or the control's own check of what is typed into it, marks it.

ui.TextInput(c, &app.card).Label("Card number").
	Invalid(app.cardTouched && app.card == "")

func (Element) Invisible added in v0.2.1

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. Hidden takes the room away too.

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 added in v0.3.0

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

func (Element) Jump added in v0.4.3

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 added in v0.2.1

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 added in v0.2.1

func (_handle Element) JustifySelf(a Align) Element

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

func (Element) KeepFocus added in v0.4.8

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) KeepOpen added in v0.8.0

func (_handle Element) KeepOpen() Element

KeepOpen keeps a menu open as its item is chosen (MenuBase, ContextMenuBase): by the pointer, Enter or Space, the item reports Clicked and stays highlighted, as a check box item flipping a setting one may flip again, or a radio item of a Group switching the theme while the menu shows it.

func (Element) KeepScrollbars added in v0.8.0

func (_handle Element) KeepScrollbars(keep bool) Element

KeepScrollbars keeps this scroll container's scroll bars showing while its content overflows it, with the pointer over it or not, rather than only while it is hovered or a bar is dragged: a view whose place in its content matters, as a long diff filling a window, shows how far down it is. The bars look and take presses as they do on hover; Scrollbars(false) and ScrollbarAxes still hide them. It applies where Scrollbars does (a code editor's State has KeepScrollbars), and is not inherited.

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) KeyShortcuts added in v0.8.0

func (_handle Element) KeyShortcuts(mods Modifiers, key Key) Element

KeyShortcuts tells assistive technology a key, with exactly the modifiers mods, that presses or focuses the element, as ARIA's aria-keyshortcuts: the window's shortcut that runs a toolbar button's command, or opens a command palette, which screen readers read with the element's name. It is written as the platform's menus write it ("⌘K" for Cmd+K on macOS, "Ctrl+K" elsewhere). It only tells the key: handle it with Shortcut on the context, or OnWindowShortcut. Call it once for each key that does.

func (Element) Keyframes added in v0.4.3

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, unless the options' NonMotion says the sequence moves nothing.

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) LabelledBy added in v0.8.0

func (_handle Element) LabelledBy(label Element) Element

LabelledBy has label, a text the view draws as the element's caption, name the element for assistive technology, in place of its Label or the text inside it, as ARIA's aria-labelledby does, and gives a click on label to the element, as HTML's <label for> does: the click focuses it, as a text input, or in a group of controls, as a RadioGroup, the one chosen, else the first, and clicks a check box, a switch or a radio button, as a Field's label does. Call it once both are built, before or after the element:

label := ui.Text(c, "Card number").TextColor(t.TextMuted)
ui.TextInput(c, &app.card).LabelledBy(label)

A label that is no text names the element by its Label.

func (Element) Lang added in v0.5.0

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 (mygo.App.Locale) unless told otherwise: a Japanese quote in a Chinese app,

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

Korean text ("ko", "ko-KR") breaks its lines between words, at spaces and after punctuation, as Korean is written and as CSS's word-break: keep-all has it, rather than between any two syllables; a word longer than a line still breaks within it. "" takes the language of the elements around it. Browsers draw text in the page's language whatever the element's.

func (Element) LayoutBounds added in v0.4.3

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 added in v0.2.1

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; 0 takes away that of the text around it, as for a number within such a label.

func (Element) Level added in v0.2.13

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 added in v0.2.1

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 added in v0.2.17

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 added in v0.4.3

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 added in v0.2.1

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 added in v0.5.0

func (_handle Element) MarginEnd(v float32) Element

func (Element) MarginStart added in v0.5.0

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 added in v0.2.1

func (_handle Element) MarginX(v float32) Element

MarginX sets the left and right margins.

func (Element) MarginY added in v0.2.1

func (_handle Element) MarginY(v float32) Element

MarginY sets the top and bottom margins.

func (Element) MaskConicGradient added in v0.8.0

func (_handle Element) MaskConicGradient(g ConicGradient) Element

MaskConicGradient masks the element and what is inside it by a conic gradient, as MaskLinearGradient does by a linear one: a ring revealed as its stops turn.

func (Element) MaskLinearGradient added in v0.8.0

func (_handle Element) MaskLinearGradient(g LinearGradient) Element

MaskLinearGradient masks the element and what is inside it by a linear gradient across its box, as CSS's mask-image: linear-gradient() does: each point shows as much as the gradient's alpha there, whatever its colors, and nothing shows outside the box (or the inset of ClipInset). A list whose rows fade out at its top and bottom edges:

black := ui.RGB(0, 0, 0)
fade := []ui.GradientStop{{ui.Transparent, 0}, {black, 0.1}, {black, 0.9}, {ui.Transparent, 1}}
list.MaskLinearGradient(ui.LinearGradient{Angle: 180, Stops: fade})

Each thing drawn is masked on its own, rather than the element drawn into a layer first, as Opacity fades a group: where the mask lets a part through, a row's background shows what is under it too.

func (Element) MaskRadialGradient added in v0.8.0

func (_handle Element) MaskRadialGradient(g RadialGradient) Element

MaskRadialGradient masks the element and what is inside it by a radial gradient, as MaskLinearGradient does by a linear one: a vignette, or a spotlight.

func (Element) Masks added in v0.8.0

func (_handle Element) Masks(layers ...Mask) Element

Masks masks the element and what is inside it by layers of masks, the first on top, each composited with those after it as its Composite says, as CSS's mask-image with mask-composite does: each point shows as much as the result's alpha there, and nothing shows outside the box (or the inset of ClipInset). It replaces MaskLinearGradient and the others, which make one layer, and they replace it. A ring 1.5 DIPs wide, of a gradient, its middle cut out by a layer over the content box:

black := ui.RGB(0, 0, 0)
solid := ui.LinearGradient{From: black, To: black}
ui.Box(c).Size(120, 40).Radius(20).Padding(1.5).Gradient(pink, violet, 90).Masks(
	ui.Mask{Image: solid, Box: ui.MaskContentBox, Composite: ui.MaskExclude},
	ui.Mask{Image: solid},
)

and a crescent, a disc less one beside it:

disc := func(x, y float32) ui.RadialGradient {
	return ui.RadialGradient{Center: ui.Point{X: x, Y: y}, Radius: 40,
		Stops: []ui.GradientStop{{black, 0.98}, {ui.Transparent, 1}}}
}
moon.Masks(ui.Mask{Image: disc(0.5, 0.5), Composite: ui.MaskSubtract}, ui.Mask{Image: disc(0.7, 0.35)})

Layers that are not one gradient across the border box make a mask of their alpha, drawn once for each size the element paints at.

func (Element) Material added in v0.2.10

func (e Element) Material(m Material) Element

func (Element) MaxHeight

func (_handle Element) MaxHeight(v float32) Element

func (Element) MaxHeightPercent added in v0.2.1

func (_handle Element) MaxHeightPercent(p float32) Element

func (Element) MaxLength added in v0.8.0

func (_handle Element) MaxLength(n int) Element

MaxLength keeps the user from making a text input's value longer than n, counted as HTML's maxlength counts it, in UTF-16 code units, a newline as one: text typed, pasted or committed by an input method is cut to what fits at the caret, and replacing a selection takes what fits in its place. A value the app sets is not cut. n <= 0 means no limit. Like ReadOnly, it holds for the input that comes until the next frame.

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 added in v0.2.1

func (_handle Element) MaxWidthPercent(p float32) Element

func (Element) MaximizeButton added in v0.6.0

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 (mygo.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 (mygo.Window.Maximize). The first such element of a frame counts; elsewhere it does nothing.

func (Element) Menu added in v0.2.5

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()
	}
})

PopoverMenuButton draws the same menu in the window, with the theme's look, as Menu does while the window draws its menus (SetMenuPresentation).

func (Element) MinHeight

func (_handle Element) MinHeight(v float32) Element

func (Element) MinHeightPercent added in v0.2.1

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 added in v0.2.1

func (_handle Element) MinWidthPercent(p float32) Element

MinWidthPercent, MinHeightPercent, MaxWidthPercent and MaxHeightPercent bound the size by a percentage of the parent's. With a bound in DIPs too, both apply: the larger minimum and the smaller maximum, as CSS's max-width: min(78%, 34rem) for a chat bubble:

ui.Box(c).MaxWidthPercent(78).MaxWidth(544)

func (Element) Mixed added in v0.2.13

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 added in v0.2.13

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) Multiline added in v0.9.0

func (_handle Element) Multiline(on bool) Element

Multiline tells assistive technology that an element of the text box role (Role(RoleTextField)) that MyGo does not edit takes several lines, as ARIA's aria-multiline. Text inputs and text areas know it themselves, from the control they are, and other roles ignore it.

func (Element) Multiselectable added in v0.8.0

func (_handle Element) Multiselectable(on bool) Element

Multiselectable tells assistive technology whether the user chooses several of the items of the element, a list, grid, tree or tree grid of your own, as ARIA's aria-multiselectable: screen readers offer to choose more than one. Its rows or items say which are chosen with Checked, or Selected, which shows it too. Lists, tables and grid views with a Selection tell it themselves.

func (Element) NoShadow added in v0.8.0

func (_handle Element) NoShadow() Element

NoShadow takes off the outer and inner shadows added so far, as CSS's box-shadow: none, so that the Shadow and InsetShadow calls after it start afresh.

func (Element) NoWrap added in v0.2.1

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) ObjectPosition added in v0.8.0

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

ObjectPosition places an Image's picture in its box where Fit leaves room around it, or crops it, as CSS's object-position: x and y are fractions of that room across and down, 0 by the left or top edge, 1 by the right or bottom one, and 0.5, as by default, in the middle. An avatar's face, near the top of its photo, stays in view with

ui.Image(c, photo).Size(40, 40).Fit(ui.Cover).ObjectPosition(0.5, 0.15)

as object-position: 50% 15%; the edge keywords are 0 and 1, as ObjectPosition(1, 0) for right top. Values beyond 0 and 1 move the picture further, past the box's edges.

func (Element) ObserveInput added in v0.8.0

func (_handle Element) ObserveInput(fn func(ev InputEvent)) Element

ObserveInput has fn see the input that comes to the element or to an element inside it, without taking it, as an ancestor listening to the keydown events that bubble up to it from the focus: keys pressed and released (with Repeat), text typed and composed, and the edit commands of the menus while the element or one of its descendants has the keyboard focus, and the pointer pressed and released over it. fn runs on the main thread before the element the input goes to gets it (the capture phase of UI Events), the outermost of the elements observing first, with X and Y relative to its own box; the input then goes on as it would without fn, to HandleInput, the text inputs, shortcuts, Tab and the rest, which may move the focus. A frame follows the input fn sees.

fn sees what HandleInput would see at the focus, whatever takes it, keys a Shortcut takes and Tab among them, but not the keys the system or the menus take before the window gets them (an edit command of the menus comes instead, InputCommand), the keys a web view takes while it has the focus, nor the input of the popovers, menus and dialogs the element opens, which are not inside it. A key that moved the focus, as Tab, comes up where the focus went, as with UI Events. A disabled element observes nothing.

It is for a region that reacts to any input in it, such as a demo that stops playing at the first key pressed in it, or a panel that closes a hint as soon as one of its fields is typed in.

func (Element) OnChange added in v0.3.0

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 added in v0.3.0

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

OnClick runs after construction and bound-value input.

func (Element) OnPaste added in v0.4.0

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 fn reads with Services.ReadClipboardData. 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.

fn runs between frames, where an Element kept from the view is no longer valid, and the input writes what it holds over its bound value, so setting the value from fn is lost. To put text of its own in place of the paste, as a link to an image it attaches, fn keeps the text and the view inserts it with ReplaceText as it is built again, which a paste seen by fn does at once:

svc := c.Services()
in := ui.TextArea(c, &app.draft).OnPaste(func(string) bool {
	img := svc.ReadClipboardData(transfer.PNG)
	if len(img.Items()) == 0 {
		return false // text pastes as usual
	}
	app.insert = app.attach(img) // "![image](https://…)"
	return true
})
if app.insert != "" {
	start, end := in.TextSelection()
	in.ReplaceText(start, end, app.insert) // a step of undo
	app.insert = ""
}

func (Element) OnShortcut added in v0.3.0

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 added in v0.3.0

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

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

func (Element) OnTextKey added in v0.5.0

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) OnUnmount added in v0.9.0

func (_handle Element) OnUnmount(fn func()) Element

OnUnmount has fn run when the element goes: once, on the main thread, after the first frame that no longer builds it, as a Local that is an io.Closer closes, without a type to give a Close. A view stops in fn the work it started, as a streaming request, a ticker or a subscription:

e := ui.Column(c)
cancel := ui.Local(e, "feed", func() context.CancelFunc {
	ctx, cancel := context.WithCancel(context.Background())
	go read(ctx, url)
	return cancel
})
e.OnUnmount(*cancel)

Call it as the element is built, after Key: each call replaces the function, and the last one given runs. A frame that does not call it keeps the one given before, and a nil fn takes it away. An element leaving with an exit transition runs fn once its exit ended, and every element as its window closes. fn may change the app's state; ask for the frame that shows it with Window.Invalidate, or Invalidate of the c.Services() the view kept.

func (Element) Opacity

func (_handle Element) Opacity(o float32) Element

Opacity makes the element and its children translucent as one group, as CSS's opacity does: what they paint is composited first and then faded, so that children overlapping one another, or the element's background under them, never show through each other. Where nothing they paint overlaps, they paint faded each on its own, which looks the same and costs nothing more; otherwise they render into a layer of the GPU first, in which text is smoothed in grayscale, as in Cache's. A web view or a material reading its backdrop inside the element shows through no layer: there each thing fades on its own. Disabled's dimming fades each thing on its own too.

func (Element) Orientation added in v0.8.0

func (_handle Element) Orientation(o Orientation) Element

Orientation tells assistive technology which way the element runs, as ARIA's aria-orientation: Vertical for a slider, separator, splitter, toolbar, tab list or menu of your own going up and down, which screen readers then read as vertical, Horizontal for one going across. It only tells it: the view lays the element out and handles its keys itself (FocusGroup). A slider or a separator told neither runs across, a separator taller than wide up and down; other elements have no orientation. A SliderBase going up says so itself (Vertical).

ui.Box(c).Size(4, 200).Draw(drawTrack).
	Role(ui.RoleSlider).Label("Volume").Range(0, 100, app.volume).
	Focusable().Orientation(ui.Vertical)

Any other value, as Horizontal|Vertical, takes it back.

func (Element) OverlayShortcut added in v0.2.13

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 added in v0.5.0

func (_handle Element) PaddingEnd(v float32) Element

func (Element) PaddingStart added in v0.5.0

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 added in v0.4.3

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. On a field around an input, as SearchField, TokenField and Combobox, it shows in the field's input, in place of the field's own: SearchField shows Search without one.

func (Element) PlaceholderColor added in v0.7.4

func (_handle Element) PlaceholderColor(color Color) Element

PlaceholderColor sets the color of this input's placeholder for this build. When unset it uses the theme's TextMuted. It does not change entered text, other inputs or the theme. A transparent color hides the placeholder.

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. The build that reads the last moves of a press on the element sees where the pointer let go.

func (Element) PopoverMenu added in v0.7.2

func (_handle Element) PopoverMenu(build func(m *Menu), options ...PopoverMenuOptions) Element

PopoverMenu gives the element a context menu, as ContextMenu does, which MyGo draws in the window with the theme's look, as a popover, rather than the system showing one of its own. It opens 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 fills it with the items ContextMenu's function takes, and the item chosen reports Chosen as there:

row.PopoverMenu(func(m *ui.Menu) {
	if m.Item("Rename").Shortcut(0, ui.KeyF2).Chosen() {
		app.renaming = i
	}
	if m.Item("Pinned").Checked(note.pinned).Chosen() {
		note.pinned = !note.pinned
	}
	m.Separator()
	if m.Item("Delete").Disabled(note.locked).Chosen() {
		app.delete(i)
	}
})

The menu takes the focus as it opens and gives it back as it closes, to the element that had it. Up and Down move among its items, past those disabled, as do Home, End and typing the first letters of an item; Right opens a submenu and Left closes it, the other way round right to left (Direction); Enter and Space choose an item, Escape closes the submenu on top, and a press outside the menu closes it. It shows below and after where it opened, and on the other side where the window has no room. Assistive technology sees a menu of items, check box items and radio items, as the system's. ContextMenuBase is such a menu without a look, for items of a layout of one's own.

PopoverMenuButton draws the menu of a menu button so.

Its options style the panel of the menu and of its submenus, and the rows of their items, as a menu button's (PopoverMenuOptions): a context menu that unfolds from where it opened, as the app's drawn menu buttons do.

func (Element) PopoverMenuButton added in v0.7.3

func (_handle Element) PopoverMenuButton(build func(m *Menu), options ...PopoverMenuButtonOptions) Element

PopoverMenuButton makes the element a menu button, as Menu does, whose menu MyGo draws in the window with the theme's look, as PopoverMenu draws a context menu, rather than the system showing one of its own. It opens below the element, or above it where the window has no room, as the pointer goes down on it, and for Enter, Space, Up or Down while it has the focus, which it takes. build fills it with the items Menu's function takes, and the item chosen reports Chosen as there:

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

The menu has the keys of PopoverMenu's, and takes the focus as it opens and gives it back as it closes, as there; a press on the element closes it too. Opened by the keyboard, it starts on its first item. Assistive technology sees a menu button, expanded while its menu shows, and the menu as PopoverMenu's. The function PopoverMenuButton is a button with such a menu, as MenuButton is one with a menu of the system's, and MenuBase a menu button without a look.

Its options place the menu elsewhere along the button, let the app open and close it, and style its panel (PopoverMenuButtonOptions): the menu of a toolbar's button at the window's end lines up with the button's end, and closes from an event of the app's:

more.PopoverMenuButton(build, ui.PopoverMenuButtonOptions{
	At: ui.AnchorBottomEnd, Self: ui.AnchorTopEnd, Open: &app.moreOpen,
})

func (Element) PositionInSet added in v0.8.0

func (_handle Element) PositionInSet(pos int, size int) Element

PositionInSet tells assistive technology which item of its set the element is, pos from 1, and how many items the set has, size, as ARIA's aria-posinset and aria-setsize: for an item of a list, list box, tree, menu or tab list of your own whose set is not what is built around it, as one built only where it shows, or a tree laid out flat in one column (with Level), so that screen readers read "3 of 50". Either at 0 or less is not given: the place the element's widget gives it, if any, stands.

for i := app.first; i < app.last; i++ { // only those in view
	ui.Row(c).Role(ui.RoleOption).PositionInSet(i+1, len(app.results)).
		Children(func() { ui.Text(c, app.results[i]) })
}

It wins over the place a ComboboxBase, SelectBase, MenuBase, Tree or GridView gives its items, which counts those it builds, as for a combobox showing the first 50 of 1,000 results. A List's rows keep theirs, which say which of all its rows they are, built or not, and place the rows of its table on macOS and Windows; a row or a cell of a grid of your own says its place with RowIndex and ColumnIndex.

func (Element) PreserveSpaces added in v0.8.0

func (_handle Element) PreserveSpaces() Element

PreserveSpaces keeps the spaces the element's text ends its lines with, and a text of only spaces, with their advance, as CSS's white-space: break-spaces does: a gap made of spaces between two texts in a row, or the padding a monospaced column is aligned with. Without it spaces ending a line take no room, as with white-space: normal.

func (Element) PressCanceled added in v0.8.0

func (_handle Element) PressCanceled() bool

PressCanceled reports whether the press of the element ended since the last frame without the pointer letting go, as Pointer Events' pointercancel: the system took it (a browser turning a touch into the page's scrolling, the window losing the mouse capture or the pointer's grab, a menu taking the release), or the window lost the keyboard. Such a press clicks nothing (Clicked) and ends no drag (DragEnded), and Pressed turns false: undo what the press began, as a preview a drag showed, rather than commit it.

dx, _, held := handle.Dragged()
switch {
case held:
	app.preview += dx
case handle.PressCanceled():
	app.preview = 0
case app.preview != 0:
	app.width, app.preview = app.width+app.preview, 0
}

func (Element) Pressed

func (_handle Element) Pressed() bool

Pressed reports whether the element is being pressed with the pointer's primary button, unless it is disabled. A press of another button, as a right-click's, is no press here, as CSS's :active and drags on the web have it: PressedButton tells which button presses the element.

func (Element) PressedButton added in v0.8.0

func (_handle Element) PressedButton() (int, bool)

PressedButton returns the button of the pointer pressing the element, 0 for the primary, 1 the secondary and 2 the middle, while the press lasts, wherever the pointer goes, as Dragged; ok is false while nothing presses it, or it is disabled. Pressed, Dragged, DragVelocity and DragEnded follow the primary button alone; an element that pans with the middle button, as a canvas, reads the button here and where the pointer goes with PointerPosition.

func (Element) PressedInside added in v0.8.0

func (_handle Element) PressedInside() bool

PressedInside reports whether the pointer went down since the last frame on the element, inside it, or in a popover attached to it, as PressedOutside reports one outside. Unlike Pressed and Clicked, the element does not take the pointer.

func (Element) PressedOutside added in v0.2.13

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. A press before the element showed, as the one opening it, is not outside it: an Overlay opened by a press stays.

func (Element) PressedPointer added in v0.8.0

func (_handle Element) PressedPointer() (PointerType, float32, bool)

PressedPointer returns the device pressing the element and how hard it presses, from 0 to 1, as of the press's last move, while the press lasts, as PressedButton; ok is false while nothing presses it, or it is disabled. As InputEvent.Pressure, a device that tells no pressure, as a mouse, presses 0.5. A signature pad widens its stroke with a pen's pressure, and goes by the pointer's speed for a mouse. Elements asking for it get a frame whenever the pointer moves or the pressure changes.

func (Element) Pretty added in v0.8.0

func (_handle Element) Pretty() Element

Pretty keeps the last line of each paragraph of the element's text from holding a single word, as CSS's text-wrap: pretty does at least: the line before gives it a word, and the lines before stay as they are. A paragraph of body text then ends on more than one word, at no cost to the rest of its lines; Balance balances them all instead.

func (Element) Query added in v0.9.1

func (_handle Element) Query(q *string) Element

Query binds *q to the text being typed in a TokenField's input, for an app that looks up suggestions as the user types, as a mail's recipients in an address book. The field writes the text to *q as Query is called, after its constructor took what was typed; what an input method is composing comes as it is committed, as in a text input's value. Adding a token clears it. Changed, asked after Query, also reports a change of the text, for the app to look up after a pause in typing, and the app passes what it found as the suggestions of a later build. The app matches them itself: the field shows them as given, in their order, leaving out only those already tokens, rather than those containing the text, so that a lookup folding accents finds Émile for "emile". Writing *q sets the input's text, as setting a text input's value does, without a change to report. With Query, assistive technology sees a combo box whose suggestions complete what was typed, even while there are none to show. Elements other than a TokenField ignore it.

to := ui.TokenField(c, &app.to, app.found).Label("To").Query(&app.query)
if to.Changed() {
	app.typedAt = c.Now() // look up once typing pauses
}

func (Element) RadialGradient added in v0.7.4

func (_handle Element) RadialGradient(g RadialGradient) Element

RadialGradient fills the element with a radial gradient, its colors spreading out from a point (CSS's radial-gradient()), as a glow:

ui.Box(c).Size(160, 100).Radius(16).RadialGradient(ui.RadialGradient{
	Stops: []ui.GradientStop{{ui.RGBA(99, 102, 241, 0.6), 0}, {ui.Transparent, 1}},
})

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 added in v0.2.13

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 added in v0.2.13

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.

On an element of your own that MyGo does not edit or operate, a widget that draws its value and handles its keys itself, it only tells assistive technology that the element is read-only, as ARIA's aria-readonly, and takes set-value, increment and decrement from it: for a text box (RoleTextField), combo box, check box, switch, slider, stepper, radio group, list box, grid or tree grid, and for the cells and headers (RoleCell, RoleColumnHeader, RoleRowHeader) of a grid or a tree grid, not of a table. Other roles, and MyGo's own controls but for the text inputs and text areas it is meant for, ignore it.

func (Element) Ref added in v0.3.0

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

Ref is an alias for Bind.

func (Element) ReplaceText added in v0.9.0

func (_handle Element) ReplaceText(start int, end int, s string) Element

ReplaceText replaces the runes of a text input from start to end with s, as an edit, a step of undo of its own: Undo brings back the text the user had, and Redo s again. A command that writes a message replaces all of it, from 0 to math.MaxInt; a completion, the word before the caret. The offsets are kept within the text, as SetTextSelection's, and what was typed in this frame is applied first. Setting the bound value instead takes the new text into the last step, which suits a reformat of what the user typed, not a text that replaces it (see TextInput). As a paste does, it puts the caret after s, and a single-line input takes line breaks as spaces; MaxLength does not cut it, as it does not cut a value the app sets. Changed reports it. It does nothing when the runes are s already.

func (Element) Reverse added in v0.2.1

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 added in v0.2.1

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) RoleDescription added in v0.8.0

func (_handle Element) RoleDescription(s string) Element

RoleDescription tells assistive technology what to call the element's role, in place of its own, as ARIA's aria-roledescription: "carousel" for a group of slides, and "slide" for each. Screen readers read it where they would read the role, so give it in the user's language, and keep the role, which says how to use the element. "" reads the role.

func (Element) Rotate added in v0.2.1

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 added in v0.4.3

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 added in v0.4.3

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) RowClicked added in v0.9.0

func (_handle Element) RowClicked() bool

RowClicked reports, while a row of a List or a Table builds, that the row was clicked since the last frame with the pointer over the element: a row's content acts on a click this way and leaves the click to the row, which goes on choosing, where Clicked would take it, so that the row's ListState.Label names what takes the click, for typing its first letters, screen readers and Tester.Click alike. It reports each click of the primary button without modifiers, on the row chosen too, and not the keys that move the choice, nor a Shift- or Cmd-click extending it. A double click reports its first click here and its second with RowDoubleClicked, as on the systems' own lists. Assistive technology pressing the row, without the pointer, reports it to the first element asking. In a list that does not choose its rows, asking makes the row take the click.

ui.List(c, &app.files, len(app.names), func(i int) {
	if ui.Text(c, app.names[i]).Padding(6, 12).FillWidth().RowClicked() {
		app.open(i)
	}
})

func (Element) RowCount added in v0.8.0

func (_handle Element) RowCount(n int) Element

RowCount tells assistive technology how many rows a table, grid or tree grid of your own has, built or not, header rows included, as ARIA's aria-rowcount: one that builds only the rows in view says how many it has, which screen readers read with the rows' RowIndex, as "row 4,121 of 10,000". The rows of a List and a Table say which of all they are themselves.

func (Element) RowDoubleClicked added in v0.6.0

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) RowIndex added in v0.8.0

func (_handle Element) RowIndex(i int) Element

RowIndex tells assistive technology the place of a row, or of a cell, among all the rows of its table, grid or tree grid, from 1 for the first, header rows included, as ARIA's aria-rowindex: for one that builds only the rows in view, with its RowCount. A cell takes its row's.

func (Element) RowSpan added in v0.2.1

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. A cell of a table or a grid tells assistive technology it covers them, as ARIA's aria-rowspan: the cells of the rows below it then say their columns with ColumnIndex where they follow it.

func (Element) RowStart added in v0.2.1

func (_handle Element) RowStart(n int) Element

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

func (Element) RowTracks added in v0.2.1

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

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

func (Element) RowWidth added in v0.3.7

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 added in v0.2.1

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

func (Element) Scale added in v0.4.3

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

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

func (Element) ScrollIntoView added in v0.2.3

func (_handle Element) ScrollIntoView(options ...ScrollIntoViewOptions) 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.

Its options line the element up elsewhere in the containers, or glide there, as the web's scrollIntoView options do: the current match of a search, centered smoothly.

if app.matchMoved {
	hit.ScrollIntoView(ui.ScrollIntoViewOptions{Block: ui.ScrollCenter, Animation: &ui.Smooth})
}

func (Element) ScrollSnap added in v0.8.0

func (_handle Element) ScrollSnap(s Snap) Element

ScrollSnap makes the scroll container (Scroll, ScrollHorizontal, ScrollBoth, List) come to rest at the places the elements in it mark with SnapAlign, as CSS's scroll-snap-type does, on the axes it scrolls:

  • a touchpad, its momentum after a fling, and a finger on a touchscreen glide on to the nearest once they have settled, and so does a thumb of a scroll bar once it is let go;
  • a notch of a wheel, the arrow keys, Page Up and Page Down, Home and End and a press on a scroll bar's track go to the next place that way, past where it was, as far as they scroll.

A place lines an element up with the container's content box, inside its padding, so that the first of a strip of cards rests where it starts. An element larger than the view rests anywhere it fills the view. Resting at an element, the container stays at it as the layout moves it, as when the window resizes, and an element of one coming into view (ScrollIntoView, the focus) lines it up. Where the app scrolls the container, with its ScrollState, ScrollTo or a List's ListState, it stays. While the desktop asks for less motion, it rests at once.

ui.ScrollHorizontal(c).ScrollSnap(ui.SnapMandatory).Padding(16).Gap(12).Children(func() {
	for _, card := range app.cards {
		cardView(c, card).SnapAlign(ui.Start)
	}
})

func (Element) ScrollWith added in v0.3.7

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) ScrollbarAxes added in v0.9.0

func (_handle Element) ScrollbarAxes(horizontal bool, vertical bool) Element

ScrollbarAxes controls the horizontal and vertical indicators and their pointer hit targets independently. Both are enabled by default, showing while the container overflows and is hovered, or as KeepScrollbars says. Hiding the axis being dragged ends that drag. Wheel, TrackScroll, keyboard focus and accessibility still scroll both axes. Scrollbars(false) hides both regardless of call order; Scrollbars(true) preserves the axis settings. It applies where Scrollbars does and is not inherited. Omitting it in the next build enables both axes again.

func (Element) ScrollbarInsets added in v0.2.15

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) ScrollbarStyle added in v0.9.0

func (_handle Element) ScrollbarStyle(s ScrollbarStyle) Element

ScrollbarStyle styles this scroll container's scroll bars, as a theme's ScrollbarStyle does every scroll bar: their track and thumb colors, the widths of their bars and thumbs, their corners and shortest thumb. Its zero fields follow the theme's, so leaving it out draws as the theme does; it applies to Scroll, ScrollHorizontal, ScrollBoth, List and Table, and is not inherited.

// As VS Code's editor: a 14 DIP square thumb in a 14 DIP bar, flush
// with its ends.
ui.Scroll(c).ScrollbarStyle(ui.ScrollbarStyle{
	TrackWidth: 14, ThumbWidth: 14, Square: true, Flush: true, MinLength: 20,
	Thumb: ui.RGBA(121, 121, 121, 0.4),
	Hover: ui.RGBA(100, 100, 100, 0.7),
	Active: ui.RGBA(191, 191, 191, 0.4),
})

func (Element) Scrollbars added in v0.7.4

func (_handle Element) Scrollbars(visible bool) Element

Scrollbars controls the overlay indicators and their pointer hit targets on this scroll container. They show on hover by default. With false, scrolling by wheel, TrackScroll, keyboard focus and accessibility remains available. It applies to Scroll, ScrollHorizontal, ScrollBoth, List and Table, not the internal indicators of custom controls such as a code editor (whose State has NoScrollbars), and is not inherited.

func (Element) Search added in v0.8.0

func (_handle Element) Search() Element

Search makes a text input one for searching, in the frames that call it, as ARIA's searchbox and HTML's <input type=search>: assistive technology reads it as a search field, as it reads a SearchField's input, while the view draws it as it likes, with an icon and a clear button of its own, and handles its keys. Name it with Label.

ui.TextInput(c, &app.query).Placeholder("Search").Label("Search mail").Search()

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 added in v0.5.0

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 added in v0.3.0

func (e Element) Selection(selection Selector) Element

func (Element) SelectionColor added in v0.2.17

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 added in v0.5.0

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 added in v0.2.17

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 added in v0.4.3

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 added in v0.4.3

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) SnapAlign added in v0.8.0

func (_handle Element) SnapAlign(a Align) Element

SnapAlign marks a place where the nearest scroll container around the element rests, if it snaps (ScrollSnap): where the element's start, center or end, as a is Start, Center or End, lines up with the container's, on both axes, as CSS's scroll-snap-align. Start is the left of what scrolls sideways, its right right to left (Direction), and the top of what scrolls vertically.

func (Element) SnapAlignX added in v0.8.0

func (_handle Element) SnapAlignX(a Align) Element

SnapAlignX marks a place as SnapAlign does, sideways only: a container that scrolls both ways rests anywhere vertically.

func (Element) SnapAlignY added in v0.8.0

func (_handle Element) SnapAlignY(a Align) Element

SnapAlignY marks a place as SnapAlign does, vertically only.

func (Element) Sort added in v0.8.0

func (_handle Element) Sort(dir SortDirection) Element

Sort tells assistive technology the order a table's rows are sorted in by the column whose header the element is (RoleColumnHeader), as ARIA's aria-sort: for a sortable table of your own, whose headers show it. Table's headers tell it from ListState.Sort and SortBy.

func (Element) SplitReset added in v0.8.0

func (_handle Element) SplitReset(v float32) Element

SplitReset makes a double click on the divider of a Split put the first pane at v, in the split's own unit: DIPs for Split and SplitVertical, a percentage for SplitPercent and SplitVerticalPercent. A split without it keeps its size on a double click. The value is kept even when the window is too small to show it, so the pane takes it back when there is room again.

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

func (Element) Spring added in v0.4.3

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 added in v0.5.0

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 added in v0.5.0

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 added in v0.2.13

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) Sticky added in v0.8.0

func (_handle Element) Sticky() Element

Sticky keeps the element in its parent's flow, where it takes its room, and holds it inside the scroll container around it while its parent is in view, as CSS's position: sticky does: Top, Right, Bottom and Left (or Start and End, and their percentages of the container's size) say how far in from the container's edges, inside its border, it stays. It moves no further than its parent's content box, so the parent leaving the view takes it along, and the next one's comes up in its place: a day's heading at the top of a timeline until the next day pushes it out, or the check box choosing all the rows at the left of a table scrolling sideways.

ui.Scroll(c).Fill().Children(func() {
	for _, day := range app.days {
		ui.Column(c).Children(func() {
			ui.Text(c, day.Title).Bold().Background(t.Surface).Sticky().Top(0)
			for _, ev := range day.Events {
				eventRow(c, ev)
			}
		})
	}
})

Each axis follows the nearest container scrolling that way, or one following another sideways (ScrollWith), or else the window: a heading in a table scrolling sideways in a page scrolling down sticks to the page's top and to the table's start. Where both insets of an axis are set and the container is too small for both, Top wins, and Left, or Right right to left. Without insets, the element stays where the flow puts it. It paints above its siblings, as Absolute elements do, and the pointer, assistive technology and the focus ring find it where it shows; the focus and assistive technology still take it in its place among them. Sticky does nothing to an Absolute element, nor to one inside a text.

func (Element) Strikethrough

func (_handle Element) Strikethrough() Element

Strikethrough strikes text through.

func (Element) Stripes added in v0.2.1

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) TabSize added in v0.8.0

func (_handle Element) TabSize(n float32) Element

TabSize puts the tab stops of the element's text every n spaces of its font from the start of each line, as CSS's tab-size: a tab advances to the next of them, as a code block indents with tabs of 2 or 4 columns. A space is as wide as the font's, letter spacing included. Without it, or with n at 0, tabs advance as the system's text stack sets them, which differs between systems.

func (Element) TabStop added in v0.8.0

func (_handle Element) TabStop(stop bool) Element

TabStop makes the element focusable, and sets whether Tab and Shift+Tab stop at it, as they do at a Focusable element. One that is no tab stop is HTML's tabindex="-1": it takes the focus from a click, from Focus and AutoFocus, and from assistive technology, while Tab passes over it, on to what is inside it and after it: a container that takes the focus to hold its keys, as a card or a dialog's panel, without coming before its own controls.

func (Element) TextAlign

func (_handle Element) TextAlign(a Align) Element

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

func (Element) TextAnchorCaret added in v0.5.2

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 added in v0.2.1

func (_handle Element) TextBackground(c Color) Element

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

func (Element) TextCaret added in v0.2.4

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 added in v0.2.17

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 added in v0.2.17

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) TextShadow added in v0.8.0

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

TextShadow casts a shadow of the element's text, as CSS's text-shadow: the shapes of its glyphs, offset by x and y DIPs, blurred by blur, in c, under the glyphs and their strokes, as a chart's labels over its bars or a caption over a photo take one to stand out. The text of the elements inside takes it too, and theirs where they set one; a transparent c casts none, where those around it cast one. A span's Shadow sets one for its text. The shadow of color glyphs, as emoji, is that of their pixels' shape; underlines and strikethroughs cast none.

ui.Text(c, "Golden hour").TextColor(ui.RGB(255, 255, 255)).TextShadow(0, 1, 4, ui.RGBA(0, 0, 0, 0.6))

func (Element) TextStroke added in v0.8.0

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

TextStroke strokes the outlines of the glyphs of text width DIPs wide in c, under their fill, as CSS's -webkit-text-stroke with paint-order: stroke fill: the half of the stroke outside the glyphs shows around them, a halo of c, as a chart's labels over its bars take one of the background's color to stand out. A text's strokes all go under all its glyphs, so that one glyph's stroke never covers its neighbor; the stroke goes around the edge of the pixels of color glyphs, as emoji. Underlines and strikethroughs are not stroked. A width of 0 strokes nothing, where the elements around it stroke their text.

func (Element) Timeline added in v0.5.0

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, unless o's NonMotion says it moves nothing, 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 added in v0.2.1

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) Touches added in v0.9.2

func (_handle Element) Touches() []Touch

Touches returns the fingers on a touchscreen that landed on the element or on an element inside it, every one down and those that lifted or were canceled since the last build, in the order they landed, unless the element is disabled. Each keeps its ID for as long as it touches, so that a view tells them apart and recognizes gestures of its own, as a whiteboard turning the page as four fingers swipe or clearing it as five tap:

for _, t := range canvas.Touches() {
	switch t.Phase {
	case ui.TouchBegan, ui.TouchMoved:
		strokes.Draw(t.ID, t.X, t.Y)
	case ui.TouchEnded, ui.TouchCanceled:
		strokes.End(t.ID)
	}
}

The fingers still do what they do without it, which apps that do not ask see alone: a tap clicks, one finger scrolls, two pinch. The window follows its fingers once a view asks: those down before, and lifting later, are not told of. Windows, Linux and browsers report touches; macOS has no touchscreens, and a trackpad's fingers, which are not points on the screen, report none. Elements asking for them get a frame whenever a finger lands, moves or lifts.

func (Element) TrackLines added in v0.3.7

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

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

func (Element) TrackScroll added in v0.2.3

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 added in v0.4.3

func (_handle Element) Transform(t Transform) Element

Transform sets the element's visual transform, in place of the one it had, TranslatePercent's included. Its origin is the center of its border box unless TransformOrigin changes it.

func (Element) TransformOrigin added in v0.4.3

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 added in v0.2.8

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 or blurs without collapsing fades and blurs in place.

func (Element) Transitioning added in v0.4.3

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 added in v0.4.3

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

Translate moves the element after its existing transform.

func (Element) TranslatePercent added in v0.8.0

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

TranslatePercent moves the element by x and y percent of its own width and height, as CSS's translate(-50%, -50%) does: of its border box as the frame lays it out, so that it is in place from its first frame and follows its size as it changes. It acts after the element's other transforms, wherever it is called among them, and before its pose (AnimatePose), and adds to a TranslatePercent before it. A callout centered above a point:

ui.Box(c).Absolute().Left(p.X).Top(p.Y).TranslatePercent(-50, -100)

func (Element) TranslateZ added in v0.8.0

func (_handle Element) TranslateZ(z float32) Element

TranslateZ moves the element z DIPs toward the viewer after its existing transform, as TranslationZ: follow it with Perspective to see it nearer or farther. A card lifting toward the viewer as it turns over:

card.RotateY(turn).TranslateZ(lift).Perspective(800)

func (Element) TruncateMiddle added in v0.9.0

func (_handle Element) TruncateMiddle() Element

TruncateMiddle puts the ellipsis of text that SingleLine or MaxLines cuts in the middle of its last line rather than at its end, so that it keeps both its start and its end, about as wide each, in the room layout gives it: a list of files shows "src/components/…/picker.go", whose folder and file's name both show. TruncateStart, with it, cuts the start instead.

func (Element) TruncateStart added in v0.9.1

func (_handle Element) TruncateStart() Element

TruncateStart puts the ellipsis of text that SingleLine or MaxLines cuts at the start of its last line rather than at its end, so that it keeps as much of its end as fits the room layout gives it: a list of files shows "…/theme/picker.go", whose file's name and nearest folders show where its start does not matter. With TruncateMiddle too, the start is cut.

func (Element) Underline

func (_handle Element) Underline() Element

Underline underlines text.

func (Element) UnderlineOffset added in v0.8.0

func (_handle Element) UnderlineOffset(v float32) Element

UnderlineOffset puts underlines v DIPs below the baseline, measured to their top, or above it when negative, as CSS's text-underline-offset: a link's underline a few pixels lower than the font puts it, clear of the descenders. Underlines skipping the ink of descenders skip it where they then are. The font places them otherwise.

func (Element) Unselectable added in v0.2.17

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 added in v0.3.0

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 added in v0.2.13

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, or the text of a range's value beside its number (aria-valuetext), as "3 of 10 steps".

func (Element) Velocity added in v0.4.3

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 added in v0.2.13

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 added in v0.2.1

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) WindowDoubleClicked added in v0.9.0

func (_handle Element) WindowDoubleClicked() bool

WindowDoubleClicked reports a double click on a DragWindow handle, which then no longer maximizes the window: the view does what a double click there means to it, as a sidebar starting something new. The handle still moves the window, which DoubleClicked would stop.

func (Element) WindowToLocal added in v0.4.3

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 added in v0.2.1

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.

func (Element) ZIndex added in v0.8.0

func (_handle Element) ZIndex(z int) Element

ZIndex orders the element's painting among its siblings, as CSS's z-index does: those with a higher value paint later, above those with a lower one, whatever their order in the tree, and take the pointer first where they overlap. Siblings with the same value paint as they would without one: those in the flow in the order they were built, then the absolute and sticky ones in theirs. The default is 0; a negative value paints the element under its siblings, still above its parent's background. The copy of an element leaving with its Exit (ElementTransition) keeps the z-index the element had, under its siblings of the same one: a dialog fading out stays above the page.

It moves the element with all that is inside it, as one, among its siblings alone: it does not reach past its parent, which still clips it where it clips, nor mix the elements inside it with those of other parents, as if each element with a value other than 0 made a stacking context, as in CSS. Nothing else changes: the layout, the order Tab moves the focus in and what assistive technology reads follow the tree.

A stack of overlapping avatars, the first on top:

ui.Row(c).Children(func() {
	for i, u := range users {
		a := ui.Avatar(c, u.Name, u.Photo).ZIndex(len(users) - i)
		if i > 0 {
			a.Margin(0, 0, 0, -8)
		}
	}
})

A cell of a grid growing as the pointer is over it, above the cells after it:

cell := ui.Box(c).Size(80, 80)
if cell.Hovered() {
	cell.Scale(1.2, 1.2).ZIndex(1)
}

The window's content stays under its overlays (Overlay) whatever its z-index, and overlays keep the order they open in; an element inside a text (inline) paints with its text.

type ElementTransition added in v0.2.8

type ElementTransition struct {
	// Duration is how long a change takes: 200 ms when zero, and none
	// when negative, which shows every change, the Enter and the Exit at
	// once, as for an app asking for less motion of its own.
	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
	// ExitDuration and ExitEase, if set, are how long the Exit takes and
	// how it goes, in place of Duration and Ease, or of Animation's spring
	// (whose Delay holds it unless ExitDelay says otherwise): a popup that
	// comes in over 150 ms and goes over 100. When zero, ExitDuration is
	// Duration's, or about as long as Animation's spring; when negative,
	// the element goes at once, without a copy. ExitEase is Ease's, or
	// that of Animation's curve, when nil.
	ExitDuration time.Duration
	ExitEase     Easing
	// ExitDelay, if set, is how long the Exit waits before it goes, in
	// place of Animation's Delay, as CSS sets transition-delay for each
	// state. When zero, the Exit waits as the other changes do; when
	// negative, it does not wait: the rows of a list that come in one
	// after another, each with a longer Delay, go all at once.
	ExitDelay time.Duration
	// Position, Size, Colors and Shadows choose what animates: where the
	// element is in its parent, its width and height (its content laid out
	// at each size on the way), its background and border colors, and its
	// shadows (Shadow, InsetShadow), as a resting shadow fading on hover.
	// None set animates them all.
	Position, Size, Colors, Shadows bool
	// Width and Height, in place of Size, animate the element's width or
	// its height alone, as CSS's transition-property lists one of them:
	// the other follows the layout at once, as a panel springing open
	// while the split view holding it is dragged wider.
	Width, Height 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 of the same z-index (ZIndex),
	// taking neither room, the pointer nor the focus, and is then gone. The parent's ChildExit, in the
	// frame it goes, says where it goes instead.
	Exit *Motion
	// AfterExits holds the element appearing while copies of its siblings
	// leave with their Exit: it takes its place unseen, and comes in with
	// its Enter once they are gone, so that its parent shows one of them
	// at a time, as a panel that finishes leaving before the next one
	// appears.
	AfterExits bool
	// 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
	// Fly, with a Match, flies the element appearing from where the other
	// was, as Keynote's Magic Move and Flutter's Hero do: from its
	// corners, opacity, text color and transform (in 3D too), and from the
	// transforms of the elements around it, drawn over the rest of the
	// window (or of its overlay) on the way, out of the clips around it,
	// where it takes the pointer. The other, flying too, goes with it,
	// fading out under it, rather than as its Exit says.
	Fly bool
	// ScaleContent shows the element's size changing, as it resizes or
	// comes from the element of its Match, by scaling it from its own size
	// rather than laying its content out at each size on the way: its text
	// keeps its lines, growing or shrinking with it, as a title into a
	// heading, and a picture stretches with its box.
	ScaleContent bool
}

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, its background and border colors, and its shadows. 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 FillRule added in v0.8.0

type FillRule uint8

FillRule is which points inside a path's subpaths a Painter fills, as SVG's fill-rule and clip-rule say, where they overlap or one is inside another.

const (
	// NonZero fills a point that the subpaths wind around more times in
	// one direction than in the other: a subpath inside another one,
	// drawn the same way round, fills too, and one drawn the other way
	// round leaves a hole. The default, as SVG's nonzero.
	NonZero FillRule = iota
	// EvenOdd fills a point that the subpaths go around an odd number of
	// times, whichever way: a subpath inside another one leaves a hole,
	// as a ring of two circles, as SVG's evenodd.
	EvenOdd
)

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 FocusOptions added in v0.9.0

type FocusOptions struct {
	// PreventScroll keeps the containers around the element where they
	// are when the focus moves to it, as the web's preventScroll does,
	// rather than scrolling them as little as shows it.
	PreventScroll bool
}

FocusOptions say how Focus gives the focus, as the web's FocusOptions do. The zero options do what Focus does without them.

type Font added in v0.2.4

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
	// LineHeight is the height of a line of text ShapeText and
	// ShapeRichText lay out, as a multiple of Size, as Element.LineHeight
	// takes it: 1.8 gives CJK prose its usual leading. 0 takes the font's
	// own. Metrics and Shape ignore it.
	LineHeight float32
	// 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 added in v0.2.4

func (f Font) Metrics() FontMetrics

Metrics returns the font's metrics.

type FontFamily added in v0.5.0

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 added in v0.5.0

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 added in v0.2.4

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 added in v0.2.4

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
	// RTL marks a glyph of a right-to-left run, as of Hebrew or Arabic,
	// whose clusters go from right to left: its cluster's first rune is
	// at the right of its advance.
	RTL bool
	// contains filtered or unexported fields
}

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

func Shape added in v0.2.4

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.

The glyphs are in visual order, on every platform, as they show from left to right: X ascends, and through a right-to-left run Cluster descends, with RTL set. Find the glyphs of a range of runes by their Cluster and Runes, not by their place in the slice; the glyphs of a cluster are next to each other.

type GradientStop added in v0.5.5

type GradientStop struct {
	Color Color
	At    float32
}

GradientStop is a color of a gradient (LinearGradient, ConicGradient, RadialGradient) 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 added in v0.2.5

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 added in v0.2.5

func (s *GridState) ScrollIntoView(item int)

ScrollIntoView scrolls the grid as little as shows item.

func (*GridState) ScrollTo added in v0.2.5

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 added in v0.3.0

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 added in v0.3.0

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 added in v0.3.0

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

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

func (*Handle) Focus added in v0.3.0

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 added in v0.3.0

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

func (Handle) Focused added in v0.3.0

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

func (*Handle) OnShortcut added in v0.3.0

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 added in v0.3.0

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

RequestFocus is an alias for Focus.

func (*Handle) SelectAll added in v0.9.1

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

SelectAll requests focus as Focus does, and selects all of the text of the text input or area, as Tab into it does: a find box opened again selects its query, and typing replaces it. It selects even when the control has the focus already.

type ImageOptions added in v0.4.7

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 {
	imagesrc.Source
}

ImageSource is what Image shows: a *Bitmap, an *SVG in its own colors, or a *native.Texture, which a native module draws into on the GPU.

func DecodeImage added in v0.7.2

func DecodeImage(data []byte) (ImageSource, error)

DecodeImage decodes a picture whose format is not known up front, as one downloaded: a bitmap of what DecodeBitmap decodes, else an SVG of a size, else DecodeBitmap's error.

type InputEvent added in v0.2.4

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
	// Code is the key by its position on any keyboard, with the sides of
	// the modifiers told apart, as CodeShiftLeft; CodeUnknown where the
	// platform does not report it, as for a mouse's side buttons, whose
	// keys are KeyBack and KeyForward. It alone names a key whose Key is
	// KeyUnknown, as a modifier on its own or Caps Lock.
	Code   KeyCode
	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
	// Canceled marks an InputPointerUp that ends the press without the
	// pointer letting go, as Pointer Events' pointercancel: the system
	// took the press (a browser's pointercancel, as a touch turns into
	// the page's scrolling, the window losing the mouse capture or the
	// pointer's grab, a menu taking the release), the window lost the
	// keyboard, or a frame built the element no more. The release still
	// comes, so that what the press holds lets go, but it is no
	// completed gesture: undo what the press began rather than commit it,
	// as a tap, a drop or the end of a scrub. Elements that ask about
	// their input as they are built get no click of it (Clicked,
	// RightClicked), no drop (Drop) and no end of a drag (DragEnded).
	Canceled bool
	// Pointer is the device of InputPointerDown, InputPointerUp and
	// InputPointerMove, and Pressure how hard it presses, from 0 to 1, as
	// Pointer Events' pointerType and pressure: a pen's or a finger's
	// where the system tells it, else, as for a mouse, 0.5 while a button
	// is down and 0 while none is. A pen's pressure changing where it
	// stands comes as an InputPointerMove too.
	Pointer  PointerType
	Pressure float32
	// DX and DY are what InputScroll scrolls by, in local axes; positive DY moves the view
	// down the content.
	DX, DY   float32
	Precise  bool
	Momentum 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 added in v0.2.4

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). Every key the system
	// tells the window of comes: a modifier on its own, a lone tap of Super
	// among them, the lock keys, and a key whose press the layout types no
	// Key for come with Key KeyUnknown, named by Code alone, and Mods holds
	// the modifier a press brings and not the one a release takes. Taking
	// one keeps it from the system, as Alt from the menu bar.
	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. One the element leaves, the
	// input method gives up on macOS, as a terminal does the dead key ´ of
	// Option-E that it sent as Alt, so that the next key isn't composed
	// with 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, or
	// once a frame builds the element no more, as when the press moved it
	// into another container, or when the system cancels the press: those
	// releases are Canceled.
	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. Momentum
	// marks scrolling that continues after the fingers leave a touchpad.
	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 KeyCode added in v0.8.0

type KeyCode uint16

KeyCode is a key by its position on the keyboard, whatever the layout types and whichever system reports it (InputEvent.Code), with the sides of the modifiers told apart and every key of a full keyboard, those that Key has no name for too. Its values are USB HID usage IDs of the keyboard page (0x07), and its names the codes of UI Events' KeyboardEvent, Meta being Super here.

type Keyframe added in v0.4.3

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 added in v0.4.3

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
	// NonMotion says that the sequence moves nothing on screen, as a
	// pulsing opacity or a blur that settles: it still plays while the
	// desktop asks for less motion, as Animation's NonMotion does.
	NonMotion bool
}

KeyframeOptions controls playback.

type LineCap added in v0.7.0

type LineCap uint8

LineCap is how a stroke ends where its subpath or a dash of it does.

const (
	// RoundCap ends a stroke in a half disc as wide as the stroke: the
	// default.
	RoundCap LineCap = iota
	// ButtCap ends a stroke square, where its line ends.
	ButtCap
	// SquareCap ends a stroke square, half its width past where its line
	// ends.
	SquareCap
)

type LineJoin added in v0.7.0

type LineJoin uint8

LineJoin is how a stroke turns at a corner of its path.

const (
	// RoundJoin turns a corner in an arc: the default.
	RoundJoin LineJoin = iota
	// MiterJoin turns a corner in a point, where the stroke's sides meet,
	// and bevels it where the point would be farther from the corner than
	// the miter limit (MiterLimit).
	MiterJoin
	// BevelJoin cuts a corner straight across.
	BevelJoin
)

type LinearGradient added in v0.2.1

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 added in v0.3.0

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

ListRow gives a row its shared context, index, selection and list focus, and what the pointer does to it: content drawing the row's hover, press or a ripple from the pointer reads them here, as the row's Element would report them, and leaves the row the one element taking the click.

func (ListRow) Hovered added in v0.9.0

func (r ListRow) Hovered() bool

Hovered reports whether the pointer is over the row, as Element.Hovered does for the row: content asking for it is built again as the pointer comes and goes, while the row keeps taking the input.

func (ListRow) ListFocused added in v0.3.0

func (r ListRow) ListFocused() bool

func (ListRow) PointerPosition added in v0.9.0

func (r ListRow) PointerPosition() (x, y float32, over bool)

PointerPosition returns the pointer's position relative to the row's box and whether it is over the row, as Element.PointerPosition does for the row: a ripple starts where Pressed first reports the press.

if row.Pressed() && app.ripple.Row != row.Index {
	x, y, _ := row.PointerPosition()
	app.ripple = Ripple{Row: row.Index, X: x, Y: y, At: time.Now()}
}

func (ListRow) Pressed added in v0.9.0

func (r ListRow) Pressed() bool

Pressed reports whether the pointer's primary button presses the row, as Element.Pressed does for the row, which takes the press: content asking for it draws the press without taking it, so a click on the row, or Tester.Click on its ListState.Label, still chooses it. In a list that does not choose its rows, asking makes the row take the press.

func (ListRow) Selected added in v0.3.0

func (r ListRow) Selected() bool

type ListState added in v0.2.4

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. Each layout reads it as it is then, so that one
	// turned off in the frame a click opens a fold in the last row keeps
	// the line clicked where it is; HoldPlace does that for one layout,
	// leaving FollowEnd on.
	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
	// MoveAnimation, when set, with a Key, makes the rows in view glide to
	// their places as rows come, go or move around them, as the animation
	// says (Smooth, a spring, or a curve), rather than jump there: a row
	// whose index changed shows where it showed, and goes on from there.
	// The rows below a row that went close its gap, and those below rows
	// that came open theirs; rows coming into view with them move with
	// them, as those a ScrollTo in the same frame brings. Scrolling moves
	// no row's index, and is not animated. Rows go to their places at once
	// where the desktop asks for less motion.
	MoveAnimation *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. With a Key, the
	// choice follows its item as rows come and go, and becomes -1 when the
	// item is no longer among the rows: the list writes that as it builds,
	// so what the app builds after the list in the same pass reads -1. An
	// app that chooses another item at the row the choice had, as rows
	// change, chooses it with Choose. An app that shows another set of rows
	// in the same list can start it afresh (list = ListState{}), which
	// forgets the item chosen before.
	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)
	// DragRows, when set, lets the user drag rows out of the list, as
	// Element.Drag drags a value: the rows chosen, when the row dragged is
	// one, else that row, which the list passes in order, drag the value
	// DragRows returns, for Drop and DragOver elsewhere to take, as a
	// folder in a list of files takes the files dropped on it. The list
	// itself takes nothing and shows no place between the rows. Return nil
	// for rows that do not drag. A list cannot both DragRows and Reorder.
	DragRows func(rows []int) any
	// 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 (or DragRows).
	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 (or DragRows).
	CellSelect bool
	// Cells are the columns of the block CellSelect chooses.
	Cells ColumnRange
	// CellsStyle paints the block of cells CellSelect chooses and the
	// rows chosen instead of the accent, as a spreadsheet's: the chosen
	// cells in a color of their own, the rest of their rows in a lighter
	// one, and every other row striped. Its zero value keeps the accent.
	CellsStyle CellsStyle
	// 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 when
	// the table's Changed reports it. It changes as the user drags a
	// header or its edge, and Changed reports it once, as the user lets
	// go, when the order or a width is new, and once a double click on
	// an edge fits a column to its cells.
	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
	// RowHeight, when above 0, is the height of every row of a Table, as
	// AppKit's rowHeight: the cells hold their content in the middle,
	// without the padding above and below that keeps a row at least the
	// theme's Space(8), so a dense table, as a source control client's or
	// a log's, shows more rows. The header keeps the theme's height.
	RowHeight float32
	// 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)
	// HeaderCell, when set, is called as a Table builds each column's
	// header cell, with the cell: what it builds goes in the cell after the
	// title and the sort arrow, as a mark, and it may give the cell a
	// tooltip or a card of its own. col is as HeaderMenu's.
	HeaderCell func(cell Element, 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)
	// EndReached, when set, is called once a frame is laid out in which the
	// user's scrolling (the wheel, a touchpad, the scroll bar, the keys, a
	// drag) brought the rows in view within NearEnd rows of the end, with
	// the last row in view: load more rows there, off the UI thread, and the
	// frames after show them. It is called as the rows in view come near the
	// end, not again while they stay there. Once they left it, or the rows
	// changed in number, as when a page loaded, the user's next scroll near
	// the end calls it again: rows coming and going do not call it by
	// themselves, nor do ScrollTo, ScrollIntoView and ScrollToEnd, the list
	// showing first, being resized or rows sorted again.
	EndReached func(last int)
	// NearEnd is how many rows before the last count as near the end for
	// EndReached: 0 for the last row alone.
	NearEnd 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 added in v0.2.4

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 added in v0.6.0

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) Choose added in v0.9.0

func (s *ListState) Choose(row int)

Choose chooses row, as setting *Selected does, -1 for none, and tells the list that the app chose it: with a Key, the list otherwise takes *Selected left at the row it chose last for its item staying chosen, and moves the choice with that item as rows come above it. Choose the row of another item that lands there, as a new file sorted above the one chosen, then chosen, and the choice stays with the new item. Call it from the view, or as the rows change. It does nothing without Selected.

func (*ListState) DragSelecting added in v0.6.0

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 added in v0.6.0

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 added in v0.2.18

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 added in v0.2.18

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 added in v0.2.18

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) HoldPlace added in v0.8.1

func (s *ListState) HoldPlace()

HoldPlace keeps the list where it is in the next layout rather than following its end, as a row opening a fold in the last message of a chat does, for the line clicked to stay under the pointer. FollowEnd stays as it is: the list follows its end again once it shows it, as when the user scrolls back to it. Call it from the view, in the frame that changes the rows.

func (*ListState) ScrollIntoView added in v0.2.4

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 added in v0.2.4

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 added in v0.2.4

func (s *ListState) ScrollToEnd()

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

func (*ListState) SelectColumns added in v0.6.0

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 added in v0.6.0

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 added in v0.2.18

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 added in v0.2.4

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 frame that changes them builds another, for what read them. To load more as the user nears the end of what was loaded, use EndReached, which the list calls after layout, rather than reading Visible as the view builds.

type Mask added in v0.8.0

type Mask struct {
	// Image is what the layer masks by: the alpha of a LinearGradient, a
	// RadialGradient or a ConicGradient across Box, whatever its colors.
	// A gradient of one color, as LinearGradient{From: black, To: black},
	// shows all of Box.
	Image MaskImage
	// Composite is how the layer goes with those after it in the list,
	// which are under it: MaskAdd, by default, shows what either shows.
	// The last layer's is not used.
	Composite MaskComposite
	// Box is the box the image lies across, nothing of the layer showing
	// outside it: the element's border box by default, or its padding box
	// or its content box.
	Box MaskBox
}

Mask is a layer of an element's mask (Element.Masks), as one image of CSS's mask-image, with its mask-composite and its mask-origin and mask-clip.

type MaskBox added in v0.8.0

type MaskBox uint8

MaskBox is the box a layer of a mask lies across (Mask.Box), as CSS's mask-origin and mask-clip.

const (
	// MaskBorderBox is the element's box, its border included.
	MaskBorderBox MaskBox = iota
	// MaskPaddingBox is the box inside its border.
	MaskPaddingBox
	// MaskContentBox is the box inside its border and padding.
	MaskContentBox
)

type MaskComposite added in v0.8.0

type MaskComposite uint8

MaskComposite is how a layer of a mask goes with the layers under it, as CSS's mask-composite: each point shows as much as the result there.

const (
	// MaskAdd shows the layer over those under it: what either shows.
	MaskAdd MaskComposite = iota
	// MaskSubtract shows the layer where those under it do not.
	MaskSubtract
	// MaskIntersect shows the layer where those under it show too.
	MaskIntersect
	// MaskExclude shows the layer and those under it where the other does
	// not: what one of them shows, but not both.
	MaskExclude
)

type MaskImage added in v0.8.0

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

MaskImage is what a layer of a mask masks by: a LinearGradient, a RadialGradient or a ConicGradient.

type Material added in v0.2.10

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/egoist/mygo/plugins/glass).

type MaterialBuilder added in v0.2.10

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, PopoverMenu, Element.Menu or PopoverMenuButton. 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. An element within text, as a link in a paragraph, opens its menu on that text. On an element of HandleTextInput, as the rich text editor, it adds the text field items too, whose commands come to its HandleInput as InputCommand. 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) MaxWidth(w float32) *Menu

MaxWidth keeps the menu, as PopoverMenu and PopoverMenuButton draw it, at most w DIPs wide: labels, subtitles and Trailing texts too long for it end with an ellipsis, while shortcuts, icons and marks keep their room. Its submenus take the same width unless their function sets one of its own; 0 lifts it, and a drawn menu is never narrower than its least width, 45 units of the theme's Spacing. Assistive technology, Tester.Menu and the letters typed to go to an item still see each label whole, and a Tooltip can show it to the pointer. The system's menus take no width from it.

ui.PopoverMenuButton(c, "Recent", func(m *ui.Menu) {
	m.MaxWidth(320)
	for _, f := range app.recent {
		if m.Item(f.Path).ID(f.Path).Tooltip(f.Path).Chosen() {
			app.open(f)
		}
	}
})
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 MenuIcon interface {
	PlatformMenuIcon() *platform.MenuIcon
}

MenuIcon is the image of a menu item, as mygo.NewMenuIcon makes it of a PNG image, and mygo.NewMenuIconSVG of an SVG document.

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: the item with the ID of the one chosen, when it had one (ID), else the one at its place with its label.

func (it *MenuItem) Content(fn func(content MenuItemContent)) *MenuItem

Content builds what the item shows in place of its label and subtitle, as PopoverMenu and PopoverMenuButton draw it: fn builds the children of a column between the item's mark and icon and its Trailing text and shortcut, as the item shows, highlighted or not (MenuItemContent). Text in it takes the color of the item's label. The item keeps its label: assistive technology reads it as the item's name, the letters typed go to it, and the system's menus show it, without the content.

m.Item("Download").Trailing("40%").Content(func(x ui.MenuItemContent) {
	ui.Text(x.Context, "Download")
	ui.Progress(x.Context, app.progress)
})

The content is part of the item, which keeps the pointer and the keys of the menu: a press on it chooses the item, closing the menu, and the pointer highlights it. A control in it takes its own presses, as a text input that a click gives the focus to, as a filter of the items after it: it keeps the focus as the pointer moves over its item, and has the keys it handles, the text typed with Space, and Enter, Home and End for a text input. Up and Down still move the highlight, giving the menu the focus back, the pointer moving onto another item does too, and Escape closes the menu. The item stays one the keys and the pointer stop at, and Enter on it, or a press beside the control, chooses it; a menu of one's own (MenuBase, ContextMenuBase) can put such a field outside its items.

func (it *MenuItem) Danger() *MenuItem

Danger shows the item in the theme's Danger color, as one that deletes or discards: its label, and its mark and template icon. Highlighted, it shows the theme's highlight, as the other items do, with its label in the Danger color where that is legible on the highlight, else in the highlight's text color (Theme.AccentText). The color alone tells no one using assistive technology: let the label say what the item does, as "Delete…". PopoverMenu draws it so; the system's menus show the item as the others.

if m.Item("Delete…").Danger().Chosen() {
	app.confirmDelete()
}
func (it *MenuItem) Disabled(d bool) *MenuItem

Disabled shows the item grayed out when d is true: it cannot be chosen.

func (it *MenuItem) Highlighted() bool

Highlighted reports whether the item is highlighted in the menu drawn in the window (PopoverMenu, PopoverMenuButton), as the pointer or the keys are on it or on an item of the submenu it opens: the menu's function can show, as it builds, what goes with the item the user is on, as a preview of a theme:

for _, th := range themes {
	item := m.Item(th.Name).ID(th.Name)
	if item.Highlighted() {
		app.preview = th
	}
	if item.Chosen() {
		app.theme = th
	}
}

The function sees the highlight of the menu's last pass, and builds again when it moves; in Content, it is the item's own as it builds. Call ID first, and give the items IDs when the items the function builds change with the highlight. It reports false for the system's menus, which tell no highlight, and as an item is chosen.

func (it *MenuItem) ID(id string) *MenuItem

ID gives the item an identity of its own, which Chosen and Highlighted match instead of the item's place and label: a label that changes while the menu shows, as a time or a count, or items before it that come and go, then keep the choice on the item. Give the items of a menu and its submenus different IDs; "" is none. In a drawn menu, ID also keys the item's row, whose highlight then stays on it as items around it come and go.

if m.Item(fmt.Sprintf("Sync %d Files", app.pending)).ID("sync").Chosen() {
	app.sync()
}
func (it *MenuItem) Icon(icon MenuIcon) *MenuItem

Icon shows an image beside the item's label, one mygo.NewMenuIcon or mygo.NewMenuIconSVG made: make each once, not as the menu builds, and give it to the items that show it. A template image takes the color of the item's text, or its IconColor in the menus MyGo draws. nil shows none. The system's menus show it as package mygo's items do (see NewMenuIcon), and browsers show none; PopoverMenu draws it on every platform.

if m.Item("Archive").Icon(archiveIcon).Chosen() {
	app.archive(msg)
}
func (it *MenuItem) IconColor(c Color) *MenuItem

IconColor draws the item's template icon (Icon) in c rather than in the color of its text, as a red trash can by a Delete item, or a status's color by its name. An icon in its own colors keeps them. While the item is highlighted, its icon takes the highlight's text color, as its label does, and a disabled item's is dimmed as its label is.

Only the menus MyGo draws show it: PopoverMenu's and PopoverMenuButton's, and ContextMenu's and Menu's in a window that draws its menus (PopoverMenus). The system's menus tint template icons themselves, in the color of their text, and leave it out.

if m.Item("Delete").Icon(trashIcon).IconColor(t.Danger).Chosen() {
	app.delete(msg)
}
func (it *MenuItem) Radio(on bool) *MenuItem

Radio shows the item as one of a group choosing one setting, as the one chosen when on is true:

for _, by := range []string{"Name", "Date", "Size"} {
	if m.Item(by).Radio(app.sort == by).Chosen() {
		app.sort = by
	}
}

Chosen reports the choice; the view marks the item chosen as it builds the menu again.

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.

func (it *MenuItem) Subtitle(s string) *MenuItem

Subtitle shows s on a second, smaller line under the item's label, as package mygo's MenuItem.Subtitle does: PopoverMenu draws it so on every platform, in the color of the shortcuts, and the system's menus show it as they show the subtitles of package mygo's items, under the label on macOS 14 and in browsers, after it elsewhere ("Label — Subtitle"). Assistive technology reads it as the item's description, before its Tooltip.

m.Item("Back Up Now").Subtitle("Last backup: 3 minutes ago")
func (it *MenuItem) Tooltip(s string) *MenuItem

Tooltip shows s as the pointer rests on the item, as Element.Tooltip does, to say what it does. The system's menus show it on macOS and Linux, as package mygo's items' ToolTip, and those of Windows and browsers show none; PopoverMenu shows it on every platform.

m.Item("Run").Shortcut(ui.Cmd, ui.KeyEnter).Tooltip("Runs the query under the caret")
func (it *MenuItem) Trailing(s string) *MenuItem

Trailing shows s at the end of the item, before its shortcut, in the color of the shortcuts, as a value beside a name: a file's size, a count. Assistive technology reads it as part of the item's description. PopoverMenu draws it; the system's menus show the label alone.

m.Item("Image.png").Trailing("2.4 MB")
type MenuItemContent struct {
	Context *Context
	// Highlighted is set while the pointer or the keys are on the item,
	// Disabled while it cannot be chosen.
	Highlighted, Disabled bool
	// Text is the color of the item's label as it shows, Muted that of its
	// shortcut and Trailing text.
	Text, Muted Color
}

MenuItemContent is what an item's Content builds with: the context, and how the item shows.

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

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

func ContextMenuBase added in v0.8.0

func ContextMenuBase(c *Context, target Element, open *bool) MenuParts

ContextMenuBase gives target a context menu without a look, which shows while *open is true, as MenuBase's: it opens where target is clicked with the secondary button, or Control-clicked on macOS, and, while target or an element inside it has the focus, below it when the menu key or Shift+F10 is pressed. Build it in Popup, as MenuBase's; it has the same keys, and assistive technology sees it so. PopoverMenu draws its menu with these parts, in the theme's look.

m := ui.ContextMenuBase(c, row, &app.rowMenu)
m.Popup(func(panel ui.Element) { ... })
func MenuBase(c *Context, open *bool) MenuParts

MenuBase creates a menu button without a look, whose menu shows while *open is true: a button that takes the focus and opens the menu as the pointer goes down on it, or for Enter, Space, Up or Down while it has the focus, and closes it when pressed again. Give the trigger children, and build the menu in Popup with Item, CheckItem, RadioItem and SubmenuItem, and the submenus with Submenu; an item's Clicked reports its choice, which closes the menu:

m := ui.MenuBase(c, &app.menuOpen)
m.Trigger.Padding(6).Radius(6).Children(func() { ui.Icon(c, dots) })
m.Popup(func(panel ui.Element) {
	panel.Padding(4).Radius(8).Background(t.Background).Border(1, t.Border)
	item := m.Item().Padding(6, 10).Radius(4)
	if item.Highlighted() {
		item.Background(t.Accent).TextColor(t.AccentText)
	}
	item.Children(func() { ui.Text(c, "Duplicate") })
	if item.Clicked() {
		app.duplicate()
	}
})

The menu has the keys of PopoverMenu's: it takes the focus as it opens, on its first item when the keyboard opened it, and gives it back as it closes; Up and Down move the highlight among its items, past those disabled, as do Home, End and typing the first letters of an item; Right opens a submenu and Left closes it, the other way round right to left (Direction); Enter and Space choose an item, Escape closes the submenu on top, and Tab and a press outside the menu close it. The pointer highlights the item it moves onto, opening its submenu. Assistive technology sees a menu button, expanded while its menu shows, and a menu of items, check box items and radio items. PopoverMenuButton draws its menu with these parts, in the theme's look.

func (_handle MenuParts) CheckItem(checked bool) Element

CheckItem creates an item, as Item does, that assistive technology sees as a check box item, checked while checked is set: flip what it shows when it is Clicked.

func (_handle MenuParts) Group(fn func(group Element)) Element

Group creates a group of the items that fn builds in the menu being built, a row that fn styles: the keys take it as one item, Up and Down moving onto it at its item checked, else its first, and Left and Right move among its items, round from the last to the first, the other way round right to left (Direction), instead of opening and closing submenus. Its items show, are highlighted by the pointer and are chosen as the others are; a row of radio items that KeepOpen, as a theme's Light, Dark and System, switches without closing the menu:

m.Group(func(row ui.Element) {
	row.Gap(4).Label("Theme")
	for _, th := range []string{"Light", "Dark", "System"} {
		item := m.RadioItem(app.theme == th).KeepOpen().Padding(4, 8)
		item.Children(func() { ui.Text(c, th) })
		if item.Clicked() {
			app.theme = th
		}
	}
})

Assistive technology sees a group, named by its Label, of the items in it, which it counts on their own. It returns the group.

func (_handle MenuParts) Item() Element

Item creates an item of the menu being built in Popup or Submenu: a row that is Highlighted while the pointer or the keys are on it, and whose Clicked reports its choice, by the pointer, Enter or Space, which closes the menu, unless KeepOpen. Give it children; Disabled leaves it out of the keys' way and of the pointer's. Assistive technology sees a menu item.

func (_handle MenuParts) Open() bool

Open reports whether the menu shows.

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

Popup shows the menu while it is open: below the trigger of a menu button, lined up with its start, or above it where the window has no room, and a context menu after where it opened, or before it, as from a corner. fn styles the panel, a column that scrolls the items past the room the window has, and builds the items in it. It returns the panel, or nil while the menu is closed.

func (_handle MenuParts) RadioItem(selected bool) Element

RadioItem creates an item, as Item does, that assistive technology sees as a radio item, the one chosen of its group while selected is set.

func (_handle MenuParts) Submenu(item Element, fn func(panel Element))

Submenu builds the submenu of item, a SubmenuItem of the menu being built, while it shows: fn styles its panel, after the item and lined up with it, and builds its items, as Popup's.

func (_handle MenuParts) SubmenuItem() Element

SubmenuItem creates an item, as Item does, that opens a submenu instead of being chosen: as the pointer moves onto it or clicks it, and for Right, Enter or Space while it is highlighted. Build the submenu with Submenu. Assistive technology sees a menu item that expands, expanded while its submenu shows.

type MenuPresentation uint8

MenuPresentation is how a window shows its popup menus (Context.SetMenuPresentation): the system's, or drawn in the window.

const (
	// SystemMenus shows popup menus as the system's, as ContextMenu and
	// Menu do by default.
	SystemMenus MenuPresentation = iota
	// PopoverMenus draws popup menus in the window with the theme's look,
	// as PopoverMenu and PopoverMenuButton draw theirs.
	PopoverMenus
)

type MeterLevels added in v0.2.5

type MeterLevels struct {
	Warning, Critical float64

	NormalColor, WarningColor, CriticalColor Color
}

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.

NormalColor, WarningColor and CriticalColor fill the bar in colors of the app's own, as a storage bar in a neutral gray until it is almost full, in place of the theme's Success, Warning and Danger: those left zero (Transparent) keep the theme's. Levels without Warning or Critical fill it in NormalColor throughout.

type Modifiers

type Modifiers uint8

Modifiers are modifier keys.

type Motion added in v0.2.8

type Motion struct {
	// X and Y move it by as many DIPs, and XPercent and YPercent by as
	// many percent of its own width and height, as TranslatePercent does.
	X, Y               float32
	XPercent, YPercent 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
	// Blur blurs it there by as many DIPs, as Element.Blur does: text or
	// an icon crossing over to another through a blur of 4 or so.
	Blur float32
	// Flip, for an element attached to another (AttachTo), mirrors X and
	// XPercent where the layout put it across its target from where it
	// was asked to go, and Y and YPercent where it put it the other way
	// down (AttachedAnchors), from the frame it appears: a menu asked
	// below its button, coming down from Y: -8, comes up from 8 where it
	// opens above it, as its Exit goes.
	Flip bool
}

Motion is where an element appearing comes from, or where one going goes, from its place in the layout.

type NativeGlassMaterial added in v0.8.0

type NativeGlassMaterial interface {
	Material
	// NativeGlass asks for the system's glass, or reports false for the
	// material's own drawing.
	NativeGlass() (NativeGlassSpec, bool)
}

NativeGlassMaterial is a Material drawn by the system where it has Liquid Glass (macOS 26 and later), instead of by the renderer: the material leaves a hole in the frame and the system's glass view, under it, shows what is under the surface, as a ui.WebView's page. The frame under the material is what the glass samples, not the elements the frame painted.

type NativeGlassSpec added in v0.8.0

type NativeGlassSpec struct {
	Style int
	Tint  Color
}

NativeGlassSpec is how a NativeGlassMaterial asks for the system's glass: its style (0 regular, 1 clear) and tint, A 0 for none.

type NativeWebView added in v0.4.0

type NativeWebView = surface.WebView

NativeWebView is a web view a window made for its content to show, as *mygo.WebView, of mygo.Window.NewWebView.

type Orientation added in v0.2.5

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 OutlineRow added in v0.8.0

type OutlineRow struct {
	// Depth is how deep the row's item is: 0 at the top. Branch tells
	// that it has children, and Open that they show.
	Depth        int
	Branch, Open bool
	// contains filtered or unexported fields
}

OutlineRow is a row of an outline as its Prefix builds it, while it builds it.

func (OutlineRow) Arrow added in v0.8.0

func (r OutlineRow) Arrow() Element

Arrow creates the row's arrow without a look: a box that opens or closes the item when clicked, with all inside it with Option (Alt), leaving the keyboard focus where it is. Size it and draw it from Open. Of an item without children, it is a box that does nothing, which keeps the rows' content in line.

type OutlineState added in v0.2.5

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,
	// without a Prefix, the theme's Space(4) when zero. It must not be
	// negative.
	Indent float32
	// Prefix, when set, builds the start of each row in place of the
	// outline's indentation and arrow, before what row builds, for rows of
	// a look of your own: r tells how deep the row's item is and whether
	// it is open, and Arrow makes the element opening and closing it. An
	// Outline's rows then have neither padding nor a gap, and center
	// what they hold; an OutlineTable's first cells keep their padding.
	Prefix func(r OutlineRow)
	// Generation, when not zero, lets the outline keep its rows from one
	// frame to the next, walking the open items again only when Open, the
	// roots or Generation change: change it, as with Generation++,
	// whenever children would return other items, or nil where it did not,
	// or the other way round. Open is seen changing through its own
	// methods, not through a copy of it sharing its items. When zero, the
	// outline walks all the open items in every frame, which costs as
	// much as they are many, and shows what children returns at once.
	Generation uint64
	// 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 added in v0.2.5

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 added in v0.2.5

func (s *OutlineState[K]) Item(row int) K

Item returns the item row i shows, in the last frame.

func (*OutlineState[K]) Rows added in v0.2.5

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 added in v0.5.2

func (p *Painter) Accelerated() bool

Accelerated reports whether the frame draws on a GPU: false where it draws in memory (with MYGO_GPU=0, without a GPU MyGo 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 added in v0.2.9

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 added in v0.2.9

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) AnimationFrameRate added in v0.7.0

func (p *Painter) AnimationFrameRate(fps float32)

AnimationFrameRate is AnimationFrame for a drawing that looks as smooth at fps frames a second as at the display's rate, as a record turning, a slow wave or a level meter: the window paints it again as often, rather than at each of the display's refreshes, 120 a second on ProMotion and many others, and has the display refresh as often where it can (macOS), for less power. The rate rounds up to one the display shows evenly, a whole number of its refreshes a frame: 60, 40 or 30 a second of a 120 Hz display's, 60 or 30 of a 60 Hz one's. The window draws at the fastest anything in it asks for: at the display's while another drawing asks for AnimationFrame or the view animates.

func (*Painter) Clip

func (p *Painter) Clip(r Rect, radius float32, fn func())

Clip restricts what fn draws to r.

func (*Painter) ClipPath added in v0.8.0

func (p *Painter) ClipPath(path *Path, fn func())

ClipPath restricts what fn draws to the inside of a path, by its FillRule (as SVG's clip-rule), its edges smoothed: a drawing cut to a polygon or to any outline, as CSS's and SVG's clip-path. Clips nest with those of Clip, and turn with a transform:

star := ui.MustParsePath("M50 0 L61 35 L98 35 L68 57 L79 91 L50 70 L21 91 L32 57 L2 35 L39 35 Z")
p.ClipPath(star, func() {
	p.FillGradient(r, ui.LinearGradient{From: gold, To: orange, Angle: 135}, 0)
})

The clip is a mask of the path's coverage, made once for each shape and size it is drawn at.

func (*Painter) Effect added in v0.2.10

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 added in v0.5.4

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 added in v0.2.15

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 added in v0.5.4

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 added in v0.5.5

func (p *Painter) FillConicGradient(r Rect, g ConicGradient, radius float32)

FillConicGradient fills a rounded rectangle with a conic gradient around it.

func (*Painter) FillGradient added in v0.2.1

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, by its FillRule.

func (*Painter) FillPathConicGradient added in v0.5.5

func (p *Painter) FillPathConicGradient(path *Path, g ConicGradient)

FillPathConicGradient fills a path with a conic gradient around its bounds.

func (*Painter) FillPathGradient added in v0.2.1

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) FillRadialGradient added in v0.7.4

func (p *Painter) FillRadialGradient(r Rect, g RadialGradient, radius float32)

FillRadialGradient fills a rounded rectangle with a radial gradient, its colors spreading out from a point of it.

func (*Painter) FillRadii added in v0.8.0

func (p *Painter) FillRadii(r Rect, radii [4]float32, c Color)

FillRadii paints a rounded rectangle whose corners have radii of their own, clockwise from the top left, as Element.Radius does.

func (*Painter) FocusRing

func (p *Painter) FocusRing(r Rect, radius [4]float32)

FocusRing draws the ring that shows the keyboard focus around r, whose corners are rounded by radius, as the theme draws it: FocusRingWidth wide, FocusRingOffset outside r, in Focus.

func (*Painter) Glyphs added in v0.2.4

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) Hole added in v0.8.0

func (p *Painter) Hole(r Rect, radii [4]float32)

Hole leaves a rounded hole in the frame, through which what is under the window's surface shows: the page of a ui.WebView, or a system's glass view that a NativeGlassMaterial places. Its own ink, as a material's, paints nothing there.

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 added in v0.4.7

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. It draws no other angle: between points that differ in both x and y, it paints the longer of the top and left edges of the box between them, the top if they are as long. StrokePolyline draws a slanted line.

func (*Painter) MeasureText added in v0.2.1

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) NativeGlassSupported added in v0.8.0

func (p *Painter) NativeGlassSupported() bool

NativeGlassSupported reports whether the window's surface draws the system's glass, as macOS 26's NSGlassEffectView does.

func (*Painter) Now added in v0.2.9

func (p *Painter) Now() time.Time

Now returns the time of the frame being painted, which drawings that move compute from.

func (*Painter) Preferences added in v0.8.0

func (p *Painter) Preferences() Preferences

Preferences returns the settings of the desktop that materials follow, as Context.Preferences does: a material that reduces its translucency or strengthens its contrast reads them here.

func (*Painter) RichText added in v0.2.1

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 added in v0.2.4

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) Scrollbar added in v0.7.4

func (p *Painter) Scrollbar(s Scrollbar, st ScrollbarState)

Scrollbar paints the track and thumb of a scroll bar, as a scroll container's, if it has anywhere to scroll.

func (*Painter) ScrollbarThumb added in v0.9.0

func (p *Painter) ScrollbarThumb(s Scrollbar, st ScrollbarState)

ScrollbarThumb paints the thumb of a scroll bar, as a scroll container's, if it has anywhere to scroll.

func (*Painter) ScrollbarTrack added in v0.9.0

func (p *Painter) ScrollbarTrack(s Scrollbar)

ScrollbarTrack paints the track of a scroll bar, if its style has one, under what a view draws on the bar: a view with marks on its bar paints the track, then the marks, then the thumb (ScrollbarThumb).

func (*Painter) ShaderEffect added in v0.5.2

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 added in v0.5.3

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) ShaderInstances added in v0.9.1

func (p *Painter) ShaderInstances(fx *scene.Effect, quads []Rect, data []float32, stride int, radius float32, in ShaderInput)

ShaderInstances paints quads, rectangles in DIPs each rounded by radius, with fx, the effect of a shader of package ui/shader reading in, in one op, which the GPU's renderers draw with one instanced draw: each quad as ShaderEffect paints a rectangle alone, its shader reading, for quad i, stride floats of data from data[i*stride:], at most scene.MaxInstanceData of them. 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 added in v0.2.1

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 the path's caps, joins and dashes (Path.Cap, Path.Join, Path.Dash): round and whole unless it sets them.

Each path is a coverage mask of its bounds, drawn on the GPU from an atlas the frame shares: it suits icons, charts and shapes. Thousands of large paths that change every frame, as the links of a node editor under a zoom that changes, can take more than the atlas holds; those still draw, on the CPU, more slowly, which is logged once. Opaque lines of StrokePolyline draw without masks on a GPU.

func (*Painter) StrokePathConicGradient added in v0.5.5

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 added in v0.2.1

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 added in v0.5.2

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, unless they are one segment, which has nothing to overlap: many lines of one, as a hatching, each stroked alone, cost no masks.

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 added in v0.2.17

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 added in v0.4.8

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 added in v0.2.10

func (p *Painter) Theme() *Theme

Theme returns the theme of the element being painted: that of the Themed around it, else the window's.

func (*Painter) Transform added in v0.4.7

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 added in v0.4.8

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 MustParsePath added in v0.8.0

func MustParsePath(d string) *Path

MustParsePath is ParsePath for path data that is part of the program: it panics when the data is in error.

func ParsePath added in v0.8.0

func ParsePath(d string) (*Path, error)

ParsePath makes a path of SVG path data, as the d attribute of an SVG path element holds it, in its units as DIPs: an icon's outline to fill with a gradient, stroke, draw in with Trim or dash with Dash, as any path a Painter draws.

check := ui.MustParsePath("M4 12l5 5L20 6")
p.Transform(ui.Scaling(2, 2), r.X, r.Y, func() {
	p.StrokePath(check.Trim(0, drawn), 2, c.Theme().Accent)
})

Its arcs and quadratic curves become cubic curves. Path data in error makes the path up to the error, as SVG draws it, which ParsePath returns with the error.

func (*Path) Bounds added in v0.5.3

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) Cap added in v0.7.0

func (p *Path) Cap(c LineCap) *Path

Cap sets how a Painter strokes the ends of the path's open subpaths and of its dashes, round by default, as SVG's stroke-linecap, and returns the path.

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) Contains added in v0.8.0

func (p *Path) Contains(x, y float32) bool

Contains reports whether the point (x, y) is inside the path, in the coordinates of its points, as a Painter fills it (FillRule): Canvas's isPointInPath. Its subpaths close, as filling closes them, and Trim keeps what it fills; its curves are flattened as a Painter flattens them at a scale of 4. A view tells with it which of a pie's segments, a map's regions or a ring's band a press is in, in its own handler or in an element's HitTest.

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) Dash added in v0.7.0

func (p *Path) Dash(offset float32, lengths ...float32) *Path

Dash sets a Painter to stroke the path in dashes, as SVG's stroke-dasharray and stroke-dashoffset, and returns the path. lengths are those of the dashes and the gaps between them in turn, in DIPs, repeated along the path, and twice over when there is an odd number of them; each subpath starts them anew, offset DIPs into them, and a dash through the start of a closed one turns there as at its other corners. A dash of no length shows its caps alone, as a dot with RoundCap. No lengths, a negative one, or lengths that add up to none stroke the path whole. As Trim trims the path, its dashes stay where they are on it.

func (*Path) FillRule added in v0.8.0

func (p *Path) FillRule(r FillRule) *Path

FillRule sets which points of the path a Painter fills, and clips to (FillPath, ClipPath), and Contains finds inside it, and returns the path: NonZero, the default, or EvenOdd, which makes a ring of two circles drawn the same way round:

var ring ui.Path
ring.Circle(50, 50, 40).Circle(50, 50, 25).FillRule(ui.EvenOdd)
p.FillPath(&ring, c.Theme().Accent)

func (*Path) Join added in v0.7.0

func (p *Path) Join(j LineJoin) *Path

Join sets how a Painter strokes the corners of the path, round by default, as SVG's stroke-linejoin, and returns the path.

func (*Path) LineTo

func (p *Path) LineTo(x, y float32) *Path

LineTo draws a line to (x, y).

func (*Path) MiterLimit added in v0.7.0

func (p *Path) MiterLimit(limit float32) *Path

MiterLimit sets how far the point of a MiterJoin may reach from its corner, in half the stroke's width, as SVG's stroke-miterlimit, and returns the path: a corner sharper than that is bevelled. It is 4 by default, which bevels corners sharper than about 29 degrees, and at least 1.

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 added in v0.5.2

func (p *Path) Reset() *Path

Reset empties the path and removes Trim, its FillRule and the stroke's caps, joins and dashes, retaining its storage.

func (*Path) Trim added in v0.4.3

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 or square caps showing a dot that comes or goes at once.

type Placement added in v0.5.0

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 added in v0.5.0

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 added in v0.5.0

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 added in v0.5.0

func AtTime(t time.Duration) Placement

AtTime starts a tween at time t of the timeline.

func WithPrevious added in v0.5.0

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 PlatformView added in v0.8.2

type PlatformView interface {
	// NativeView returns the view, an NSView* on macOS, or 0 once it is
	// closed.
	NativeView() uintptr
}

PlatformView is a view of the platform, which NativeView shows: a value of a native module's interface that embeds native.View.

type Point added in v0.2.17

type Point struct{ X, Y float32 }

Point is a position in DIPs relative to an element or text layout.

type PointerAccuracy added in v0.8.0

type PointerAccuracy uint8

PointerAccuracy is how accurately a pointing device points.

const (
	// PointerFine is a mouse's, a touchpad's or a pen's: the default.
	PointerFine PointerAccuracy = iota
	// PointerCoarse is a finger's on a touch screen, which wants larger
	// targets.
	PointerCoarse
	// PointerNone is that of no pointing device, as a keyboard alone.
	PointerNone
)

type PointerType added in v0.8.0

type PointerType uint8

PointerType is the kind of device moving the pointer, as Pointer Events' pointerType.

type PopoverMenuButtonOptions added in v0.8.1

type PopoverMenuButtonOptions struct {
	// At and Self place the menu as AttachTo places an element, its point
	// Self on the point At of the button's box: AnchorBottomEnd and
	// AnchorTopEnd line it up with the button's end, below it;
	// AnchorTopStart and AnchorBottomStart, or AnchorTopEnd and
	// AnchorBottomEnd, put it above the button; AnchorTopEnd and
	// AnchorTopStart put it after the button, beside it. Where the window
	// has no room, it goes to the other side of the button, or the other
	// way along it, as AttachTo's elements do, keeping its gap from the
	// button. Both zero (AnchorTopLeft) are the default, AnchorBottomStart
	// and AnchorTopStart. A menu opened at a point, as a toolbar's
	// overflow menu opens its buttons' menus, shows there instead.
	At, Self Anchor
	// Open, when set, is whether the menu shows, as MenuBase's open: the
	// button sets it as the menu opens and closes, and the app opens the
	// menu by setting it to true and closes it by setting it to false
	// before the button is built, as an event of the app's in the
	// background does before it updates the window. A menu opened so
	// takes the focus, with no item highlighted, and gives it back as it
	// closes. A window shows one such menu at a time: another opening
	// closes it, which sets *Open to false, as a disabled button, which
	// opens none, does.
	Open *bool
	// Panel, when set, styles the panel of the menu and of each submenu
	// that opens, after the theme's look and with the same calls, so the
	// app's background, border, radius or padding take its place, and its
	// shadow too after NoShadow, as Shadow adds one:
	//
	//	ui.PopoverMenuButtonOptions{Panel: func(panel ui.Element) {
	//		panel.Background(app.menuColor).Radius(12).
	//			NoShadow().Shadow(0, 18, 50, 0, ui.RGBA(0, 0, 0, 0.45))
	//	}}
	//
	// The menu keeps its place, its gap from the button and its items'
	// look: Panel sets no margin and adds no children.
	Panel func(panel Element)
	// Item, when set, styles the row of each item of the menu and of its
	// submenus, after the theme's look and with the same calls, as Panel
	// does the panel: a slimmer row, say, or other corners.
	//
	//	ui.PopoverMenuButtonOptions{Item: func(item ui.Element) {
	//		item.Padding(4, 8).Radius(6)
	//	}}
	//
	// The row keeps its content and the theme's highlight; Item adds no
	// children.
	Item func(item Element)
}

PopoverMenuButtonOptions are how a menu button whose menu MyGo draws in the window (PopoverMenuButton) shows it. The zero options show it below the button, lined up with its start, opened and closed by the user alone.

type PopoverMenuOptions added in v0.9.2

type PopoverMenuOptions struct {
	// Panel, when set, styles the panel of the menu and of each submenu
	// that opens, after the theme's look and with the same calls, as
	// PopoverMenuButtonOptions.Panel does a menu button's: it sets no
	// margin and adds no children, and the menu keeps its place.
	Panel func(panel Element)
	// Item, when set, styles the row of each item of the menu and of its
	// submenus, after the theme's look, as PopoverMenuButtonOptions.Item.
	Item func(item Element)
}

PopoverMenuOptions are how a context menu MyGo draws in the window (PopoverMenu) looks. The zero options give it the theme's look.

type Popup uint8

Popup is the kind of popup an element opens (Element.HasPopup), as ARIA's aria-haspopup says.

const (
	// PopupNone opens no popup.
	PopupNone Popup = iota
	// PopupMenu opens a menu, aria-haspopup="menu" (or "true").
	PopupMenu
	// PopupListBox opens a list of options, as a select's.
	PopupListBox
	// PopupTree opens a tree, PopupGrid a grid, as a date picker's
	// calendar, and PopupDialog a dialog.
	PopupTree
	PopupGrid
	PopupDialog
)

type Pose added in v0.4.3

type Pose struct {
	X, Y, Scale, Rotate, Fade float32
	XPercent, YPercent        float32
}

Pose is where an element shows, from its place in the layout, which AnimatePose moves it to: moved by X and Y DIPs, and by XPercent and YPercent percent of its own width and height, as TranslatePercent moves it, 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 added in v0.2.5

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
	// ReduceTransparency asks for opaque surfaces in place of translucent
	// ones: macOS's Reduce Transparency, Windows's transparency effects
	// turned off. Materials should fall back to an opaque surface, as the
	// glass plugin does; windows' own materials follow it already.
	ReduceTransparency 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
	// Pointer is how accurately the primary pointing device points, and
	// AnyPointer the most accurate of all, as Media Queries 4's pointer
	// and any-pointer: PointerFine for a mouse, a touchpad or a pen,
	// PointerCoarse for a touch screen alone, or in Windows's tablet mode.
	// A touch-first layout, with larger targets, reads Pointer; macOS's
	// and those not known are a mouse's.
	Pointer, AnyPointer PointerAccuracy
	// NoHover tells that the primary pointing device cannot hover, as a
	// finger on a touch screen, and NoAnyHover that none can: Media
	// Queries 4's hover: none and any-hover: none. Hover and AnyHover say
	// the opposite. Tooltips and what shows on hover alone want a pointer
	// that hovers.
	NoHover, NoAnyHover bool
}

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.

func (Preferences) AnyHover added in v0.8.0

func (p Preferences) AnyHover() bool

AnyHover reports whether any pointing device can hover, as Media Queries 4's any-hover: hover.

func (Preferences) Hover added in v0.8.0

func (p Preferences) Hover() bool

Hover reports whether the primary pointing device can hover, as Media Queries 4's hover: hover.

type RadialGradient added in v0.7.4

type RadialGradient struct {
	Stops []GradientStop
	// Center is the point the colors spread from, in fractions of the
	// box's width and height from its top left corner; the zero Point is
	// its middle, as ConicGradient's is.
	Center Point
	// Radius is how far the gradient reaches from its center, in DIPs; 0
	// reaches the corner of the box farthest from the center, as CSS's
	// farthest-corner default does. The gradient shows its first color
	// before the center and its last past the radius.
	Radius float32
	// Oklab mixes the colors in the Oklab color space, as LinearGradient's
	// does.
	Oklab bool
}

RadialGradient blends colors outwards from a point, as CSS's radial-gradient() does (SwiftUI's RadialGradient, Flutter's RadialGradient): its stops at their places from its center, at 0, to a circle of its radius, at 1.

e.RadialGradient(ui.RadialGradient{Stops: []ui.GradientStop{{white, 0}, {ui.Transparent, 1}}})

type Recorder added in v0.9.1

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

A Recorder builds the frames of a view without a window, one after another at the times its caller gives, as the frames of a video are made (plugins/render). Each frame is built anew at its own time, which the view's clock reads: what moves with time (Animate, Spring, a Transition, After) is where it would be on screen at that time, however long a frame takes to make, and the same frames come every time.

A Recorder is not safe for concurrent use: one goroutine makes its frames. Recorders on different goroutines run in parallel, each with a text system of its own, as Testers do.

func NewRecorder added in v0.9.1

func NewRecorder(view func(c *Context), o RecorderOptions) *Recorder

NewRecorder returns a Recorder of view, in frames of the size o gives.

func (*Recorder) Close added in v0.9.1

func (r *Recorder) Close()

Close drops what the view keeps, its states and Locals, and the last frame.

func (*Recorder) Frame added in v0.9.1

func (r *Recorder) Frame(at time.Duration) *scene.Scene

Frame builds, lays out and paints the frame at time at from the first frame's, and returns it for a renderer to draw: it stays as it is until the next call. Times go forward from frame to frame, as a window's do; one earlier than the last frame's is taken as that time.

A frame that asks to be built again at once, as a view that measures what it built and builds again (Context.Invalidate), is built again at the same time, a few times at most, so that each frame shows what it settles on.

func (*Recorder) Now added in v0.9.1

func (r *Recorder) Now() time.Time

Now returns the time of the frame being made, or of the last one: the view's clock.

func (*Recorder) Size added in v0.9.1

func (r *Recorder) Size() (w, h int)

Size returns the size of the frames in device pixels.

type RecorderOptions added in v0.9.1

type RecorderOptions struct {
	// Width and Height are the size of the frames, in device pixels.
	Width, Height int
	// Scale is how many device pixels a DIP is, 1 when zero: the view
	// lays out in Width/Scale × Height/Scale DIPs.
	Scale float32
	// Dark builds the view in the dark appearance, and Preferences with
	// the desktop's settings that controls follow.
	Dark        bool
	Preferences Preferences
	// Locale is the language the view shows (Context.Locale), "" for the
	// system's default, and Direction lays the view out right to left
	// when it is RightToLeft.
	Locale    string
	Direction Direction
	// FrameRate is how many frames a second the Recorder is asked for,
	// which the view reads as the display's refresh rate: 60 when zero.
	FrameRate float64
}

RecorderOptions describe the window a Recorder's view is built in.

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 added in v0.3.0

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 is a link: focused, it takes Enter but not Space, which
	// scrolls, as in a web page.
	RoleLink
	RoleCheckBox
	RoleRadio
	RoleSwitch
	RoleSlider
	RoleProgress
	RoleTextField
	RoleImage
	RoleList
	RoleScroll
	RoleDialog
	RolePopup
	RoleTooltip
	RolePopUpButton
	RoleTabList
	RoleTab
	RoleSplitter
	// RoleStatus is a live region of advisory information, as "3 rows
	// selected" or "Saved": when its text changes, screen readers read the
	// whole of it out, politely, after what they are reading. Give it a
	// Key when elements come before it, so that it is the same status from
	// frame to frame. What a status shows as assistive technology comes,
	// or as it first shows, is not read.
	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
	// RoleRegion is a landmark with a Label, as an activity feed or a
	// panel: screen readers list it among the window's landmarks, and
	// jump to it. Without a Label it is a group, as ARIA's region.
	RoleRegion
	// RoleLog is a live region of messages added in order, as a chat's
	// transcript: screen readers read out what is added to it, once it has
	// shown, after what they are reading.
	RoleLog
	// RoleTimer counts time, as a countdown, whose changes screen readers
	// read only when the user goes to it.
	RoleTimer
	// RoleAlert is a live region of important news, as a field's error:
	// screen readers read its content out at once, interrupting what they
	// are reading, as it appears and whenever it changes.
	RoleAlert
	// RoleSeparator divides groups of content or controls, as a rule
	// between a toolbar's groups of buttons (a Divider): screen readers
	// read it as running up and down when it is taller than wide.
	RoleSeparator
	// RoleRowHeader is the cell naming its row of a table, as
	// RoleColumnHeader names a column.
	RoleRowHeader
	// RoleSearch is a landmark holding what searches the app or a
	// document, as the search field and its button at the top of a
	// window: screen readers list it among the window's landmarks, and
	// jump to it.
	RoleSearch
	// RoleArticle is a self-contained piece of content, as a post of a
	// feed or a comment of a thread, named by its Label: screen readers
	// step from one article to the next, as HTML's article.
	RoleArticle
	// RoleNavigation is a landmark holding links that move around the
	// app or a document, as a breadcrumb trail (Breadcrumbs) or a
	// navigation bar: screen readers list it among the window's
	// landmarks, and jump to it.
	RoleNavigation
	// RoleGrid is a table whose cells take the focus and the arrow keys,
	// as a spreadsheet's, where RoleTable is one to read; RoleTreeGrid is
	// a grid whose rows open and close as a tree's items do (Expanded,
	// Level). Their rows, cells and headers are RoleRow, RoleCell,
	// RoleColumnHeader and RoleRowHeader, as a table's, and the rows of a
	// List shown as one are its rows.
	RoleGrid
	RoleTreeGrid
	// RoleListBox is a list of options to choose from, as ARIA's listbox,
	// and RoleOption one of its options, selected with Checked, as ARIA's
	// aria-selected: what a list of your own offers, such as suggestions
	// at a text area's caret whose highlighted one the text area points
	// at with ActiveDescendant. The popups of SelectBase and ComboboxBase
	// are list boxes.
	RoleListBox
	RoleOption
	// RoleDeletion and RoleInsertion hold content removed from or added
	// to a document, as HTML's del and ins, ARIA's deletion and
	// insertion: the removed and added lines of a diff, or an old price
	// struck out beside the new one. Screen readers read their text with
	// "deletion" or "insertion" rather than as plain text. They take no
	// Label: the text inside them is what they hold.
	//
	//	ui.Row(c).Gap(6).Children(func() {
	//		ui.Text(c, "$40").Strikethrough().Role(ui.RoleDeletion)
	//		ui.Text(c, "$30").Role(ui.RoleInsertion)
	//	})
	RoleDeletion
	RoleInsertion
	// RoleTabPanel holds the content of a tab, as ARIA's tabpanel does in
	// its Tabs pattern: name it after its tab with Label (or LabelledBy,
	// a text), and have the tab point to it with Controls, so that screen
	// readers can move between a tab and its content.
	//
	//	panel := ui.Column(c).Role(ui.RoleTabPanel).Label("Settings").Children(content)
	//	tab.Controls(panel)
	RoleTabPanel
	// RoleMain is the landmark holding the main content of a window, as
	// HTML's main: what the window is for, apart from its bars and
	// sidebars. A window has one, and a Label is not needed. Screen
	// readers list it among the window's landmarks, and jump to it.
	RoleMain
	// RoleBanner is the landmark holding the top bar of a window, with
	// the app's name or the window's title, as a page's header. A window
	// has at most one. Screen readers list it among the window's
	// landmarks, and jump to it.
	RoleBanner
	// RoleContentInfo is the landmark holding information about the
	// content of a window, as its footer or status area (the document's
	// word count, its author, a copyright), as a page's footer. A window
	// has at most one. Screen readers list it among the window's
	// landmarks, and jump to it.
	RoleContentInfo
	// RoleComplementary is the landmark holding content that completes
	// the main content and makes sense on its own, as a sidebar of
	// related items or an inspector, as HTML's aside. Name it with Label
	// when a window has several. Screen readers list it among the
	// window's landmarks, and jump to it.
	RoleComplementary
)

type Route added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

func (_handle *Route) Page() Element

Page returns the element holding the page, a column filling the router, for its style.

func (*Route) Param added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

func (r *Route) Query(name string) string

Query returns the value of the query parameter name, "" if the page has none.

func (*Route) Title added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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, and 300
	// ms as they fade into each other (TransitionMatch).
	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 added in v0.2.5

func NewRouter(path string) *Router

NewRouter returns a router showing the page at path.

func (*Router) Back added in v0.2.5

func (r *Router) Back()

Back shows the page before, if any.

func (*Router) CanGoBack added in v0.2.5

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 added in v0.2.5

func (r *Router) CanGoForward() bool

func (*Router) Forward added in v0.2.5

func (r *Router) Forward()

Forward shows the page after, which Back left, if any.

func (*Router) Go added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

func (r *Router) Path() string

Path returns the path of the page shown, as "/notes/42", without its query.

func (*Router) Push added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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 added in v0.2.5

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)

MyGo 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, markers, text in the system's fonts, and style sheets of type, class, id and :root selectors with descendant and child combinators, custom properties (var()) and prefers-color-scheme media queries, which follow the theme (WithDark). It leaves out embedded images, patterns and filters, which Unsupported lists.

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) Image added in v0.8.1

func (s *SVG) Image(w, h int, current color.Color) *image.RGBA

Image draws the SVG in its own colors to an image of w by h pixels, fitting it in them as its preserveAspectRatio says, with current for currentColor, black when nil: for what takes pixels rather than an element, as mygo.NewMenuIconSVG draws a menu's icon. Painter.Icon and Icon draw it in the window, at the display's scale.

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.

func (*SVG) Unsupported added in v0.9.1

func (s *SVG) Unsupported() []string

Unsupported lists what the SVG has that MyGo leaves out when it draws it, sorted: elements as "<pattern>", properties as "filter", at-rules as "@font-face", media features as "@media (min-width: 600px)" and selectors as "selector a + b". It is empty when MyGo draws all of the SVG. An app showing SVGs it did not make, as in a diff, can show a note, or another view, where it is not:

if missing := s.Unsupported(); len(missing) > 0 {
	ui.Text(c, "Not shown: "+strings.Join(missing, ", ")).Muted()
}

func (*SVG) WithDark added in v0.9.1

func (s *SVG) WithDark(dark bool) *SVG

WithDark returns the SVG drawn in the dark color scheme when dark, and in the light one otherwise, wherever it shows: its style sheets' media queries for prefers-color-scheme: dark match the dark one. An SVG ParseSVG returns follows the theme (Theme.Dark) where Image shows it, as a page follows the system's appearance, and Image (the method) draws it light; this one does not, for an app whose own setting, or whose pictures' backgrounds, say otherwise. Both share the parsed document.

type ScrollAlign added in v0.8.0

type ScrollAlign uint8

ScrollAlign is where ScrollIntoView lines an element up in a container on an axis, as the web's ScrollLogicalPosition.

const (
	// ScrollNearest scrolls as little as shows the element: not at all
	// when it shows, and to the nearer edge otherwise. What is larger than
	// the view shows from its start.
	ScrollNearest ScrollAlign = iota
	// ScrollStart lines the element's start up with the container's: its
	// top, or its left (its right, right to left).
	ScrollStart
	// ScrollCenter puts the element in the middle of the container.
	ScrollCenter
	// ScrollEnd lines the element's end up with the container's.
	ScrollEnd
)

type ScrollIntoViewOptions added in v0.8.0

type ScrollIntoViewOptions struct {
	// Block and Inline line the element up in each container around it,
	// vertically and sideways, as the web's block and inline do:
	// ScrollNearest scrolls as little as shows it, and ScrollStart,
	// ScrollCenter and ScrollEnd line its start, center or end up with
	// the container's, inside its border. Right to left, the inline start
	// is at the right.
	Block, Inline ScrollAlign
	// Animation, when set, glides the containers there as it says (Smooth,
	// a spring, or a curve), as the web's behavior: "smooth" does, rather
	// than at once. The user scrolling, or the app, stops it. While the
	// desktop asks for less motion, or the frame disables animations, it
	// scrolls at once.
	Animation *Animation
}

ScrollIntoViewOptions say where ScrollIntoView brings an element in the containers around it, and how, as the web's ScrollIntoViewOptions do. The zero options scroll as little as shows it, at once, as ScrollIntoView does without them.

type ScrollState added in v0.2.3

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 added in v0.4.3

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 added in v0.4.3

func (s *ScrollState) Scrolling() bool

Scrolling reports whether a ScrollTo is on its way.

type Scrollbar added in v0.7.4

type Scrollbar struct {
	// Box is the view the bar runs along, at its right edge, or its
	// bottom edge for a horizontal bar, in the coordinates the bar is
	// painted or hit tested in.
	Box Rect
	// Horizontal makes the bar run along the bottom, scrolling sideways.
	Horizontal bool
	// View is the length of the content the view shows, Content the
	// length of all of it, and Offset how far it is scrolled, in any
	// unit, as rows of a terminal's scrollback: the bar shows nothing
	// unless Content is longer than View.
	View, Content, Offset float32
	// Style is how the bar looks: its track and thumb colors, widths,
	// corners and shortest thumb. Its zero fields follow the theme, as
	// Theme.ScrollbarStyle does; a view that paints its own bar sets it
	// to the style it resolves, so that Thumb and OffsetAt lay out the
	// same thumb Painter.Scrollbar paints.
	Style ScrollbarStyle
}

Scrollbar is the scroll bar of a view that scrolls itself rather than through a scroll container, as a code editor or a terminal does, laid out and painted as a scroll container's are, so that every bar of an app looks alike and follows the theme (Theme.Scrollbar, ScrollbarWidth and ScrollbarStyle).

The view paints the bar with Painter.Scrollbar while it shows it: a scroll container's show while the pointer is over the container or drags a thumb, and maps a drag of the thumb to an offset with Thumb and OffsetAt.

bar := ui.Scrollbar{Box: r, View: viewH, Content: contentH, Offset: scrollY}
if hovered || dragging {
	p.Scrollbar(bar, ui.ScrollbarState{Hovered: hovered, Dragging: dragging})
}

func (Scrollbar) OffsetAt added in v0.7.4

func (s Scrollbar) OffsetAt(start float32) float32

OffsetAt returns the offset that brings the thumb's start to start, as the thumb is dragged, within the content.

func (Scrollbar) Scrolls added in v0.7.4

func (s Scrollbar) Scrolls() bool

Scrolls reports whether the bar has anywhere to scroll, and so shows.

func (Scrollbar) Thumb added in v0.7.4

func (s Scrollbar) Thumb() (start, length float32)

Thumb returns where the thumb starts along the bar, as Box's X for a horizontal bar, else its Y, and how long it is.

type ScrollbarState added in v0.7.4

type ScrollbarState struct {
	Dragging bool
	Hovered  bool
	Color    Color
}

ScrollbarState is how a Scrollbar paints: Dragging while the pointer drags its thumb, which widens it, as a scroll container's; Hovered while the pointer is over the bar, which colors it as Hover does; Color, if not zero, colors it for a view whose colors are not the theme's, as a terminal's, in place of the style's thumb colors.

type ScrollbarStyle added in v0.9.0

type ScrollbarStyle struct {
	// TrackWidth is the width of the bar's track and hit area, in DIPs. 0 is
	// ThumbWidth + 6, the thumb with 3 DIPs on either side.
	TrackWidth float32
	// ThumbWidth is the width of the thumb, in DIPs. 0 is the theme's
	// ScrollbarWidth, 6 by default.
	ThumbWidth float32
	// Radius rounds the thumb's corners, in DIPs. 0 is half ThumbWidth,
	// unless Square.
	Radius float32
	// Square leaves the thumb's corners square, as VS Code's scroll bar
	// does. A Radius set with it rounds them instead.
	Square bool
	// Flush leaves no gap between the thumb and the ends of its track, as
	// VS Code's scroll bar; otherwise it keeps 2 DIPs clear at each end.
	Flush bool
	// MinLength is the shortest the thumb gets, in DIPs. 0 is 24.
	MinLength float32
	// Track fills the bar behind the thumb; zero paints none.
	Track Color
	// Thumb colors the thumb at rest, Hover while the pointer is over the
	// bar, and Active while it is dragged. Zero Thumb takes the theme's
	// Scrollbar; zero Hover and Active take Thumb.
	Thumb, Hover, Active Color
}

ScrollbarStyle is how scroll bars look: the widths of their bars and thumbs, how round their corners are, the shortest thumb, and the colors of their tracks and thumbs at rest, hovered and dragged. A zero field follows the theme: Theme.ScrollbarStyle, and Theme.Scrollbar and Theme.ScrollbarWidth for the thumb's color and width.

Set it in a theme for every scroll bar of the app, on a scroll container (Element.ScrollbarStyle) for that container's, or on a view that paints its own bar (Scrollbar.Style), as the code editor's State.Scrollbar does.

// As VS Code's editor: a 14 DIP square thumb in a 14 DIP bar, flush
// with its ends.
t.ScrollbarStyle = ui.ScrollbarStyle{
	TrackWidth: 14, ThumbWidth: 14, Square: true, Flush: true, MinLength: 20,
	Thumb: ui.RGBA(121, 121, 121, 0.4),
	Hover: ui.RGBA(100, 100, 100, 0.7),
	Active: ui.RGBA(191, 191, 191, 0.4),
}

func (ScrollbarStyle) Resolve added in v0.9.0

func (s ScrollbarStyle) Resolve(t *Theme) ScrollbarStyle

Resolve returns s with its zero fields filled from t, as Painter.Scrollbar and scroll containers paint it: TrackWidth is ThumbWidth + 6, ThumbWidth the theme's ScrollbarWidth, Radius half ThumbWidth (or 0 with Square), MinLength 24, Thumb the theme's Scrollbar, and Hover and Active Thumb. A nil t is a zero theme.

type SegmentedParts added in v0.2.5

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

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

func SegmentedBase added in v0.2.5

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 added in v0.2.5

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, past those disabled, as do Home and End; 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 SelectBaseOpen added in v0.8.0

func SelectBaseOpen[T comparable](c *Context, selected *T, open *bool) SelectParts[T]

SelectBaseOpen is SelectBase whose popup shows while *open, a flag the caller owns, as PopoverBase's: the select sets it as it opens and closes, and the caller may set it too, as typing on the closed trigger opens the popup, or Tab moving on closes it. The highlight starts on the choice each time the popup opens. Owning the flag, the caller can keep the popup a little longer as it closes, to shrink it back into the trigger.

func (SelectParts[T]) Highlight added in v0.2.13

func (_handle SelectParts[T]) Highlight(value T)

Highlight moves the highlight to the option of value while the popup shows, unless it is disabled, as a select of your own may do as the user types the option's first letters; Enter then chooses it. Called before Popup as the popup opens, it highlights the option once Popup builds 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. Disabled leaves it out of the keys' way and of the pointer's. The option the highlight moves to scrolls into view, once, so that the wheel scrolls on past it. Assistive technology reads it as an option of a list box (RoleOption), selected while it is highlighted, as a native select's; focusing it highlights it, and pressing it chooses 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.

func (SelectParts[T]) SetOpen added in v0.8.0

func (_handle SelectParts[T]) SetOpen(o bool)

SetOpen opens or closes the popup, as typing on the closed trigger may open it, or Tab moving on close it. It opens with the highlight on the choice, which Highlight then moves.

type SelectedText added in v0.5.0

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 added in v0.2.5

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 added in v0.2.5

func (s *Selection[K]) Add(k K)

Add chooses the row of key k.

func (*Selection[K]) All added in v0.2.5

func (s *Selection[K]) All() iter.Seq[K]

All returns the keys of the rows chosen, in no order.

func (*Selection[K]) Clear added in v0.2.5

func (s *Selection[K]) Clear()

Clear chooses no row.

func (*Selection[K]) Has added in v0.2.5

func (s *Selection[K]) Has(k K) bool

Has reports whether the row of key k is chosen.

func (*Selection[K]) Len added in v0.2.5

func (s *Selection[K]) Len() int

Len returns how many rows are chosen.

func (*Selection[K]) Remove added in v0.2.5

func (s *Selection[K]) Remove(k K)

Remove takes the row of key k out of the choice.

type Selector added in v0.2.5

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

A Selector is what ListState.Selection takes: a *Selection.

type Services added in v0.3.0

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 added in v0.5.0

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 added in v0.3.0

func (s Services) Invalidate()

func (Services) OpenURL added in v0.3.0

func (s Services) OpenURL(url string)

func (Services) ReadClipboard added in v0.3.0

func (s Services) ReadClipboard() string

func (Services) ReadClipboardData added in v0.5.0

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 added in v0.3.0

func (s Services) WriteClipboard(text string)

func (Services) WriteClipboardData added in v0.5.0

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 added in v0.5.4

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 Snap added in v0.8.0

type Snap uint8

Snap is how a scroll container comes to rest at the places the elements in it mark (ScrollSnap), as CSS's scroll-snap-type.

const (
	// SnapNone, the zero value, rests wherever the scrolling stops.
	SnapNone Snap = iota
	// SnapMandatory always rests at a place, as CSS's mandatory: a strip
	// of cards rests showing a card from its start, and a notch of a
	// wheel or an arrow key goes on to the next card.
	SnapMandatory
	// SnapProximity rests at a place only where the scrolling stops
	// near it, within a third of the view, as CSS's proximity, and
	// wherever it stops in between.
	SnapProximity
)

type SortDirection added in v0.8.0

type SortDirection uint8

SortDirection is the order a table's rows are sorted in by a column (Element.Sort), as ARIA's aria-sort says.

const (
	// SortNone is not sorted by the column.
	SortNone SortDirection = iota
	// SortAscending and SortDescending sort the rows up or down the
	// column's values.
	SortAscending
	SortDescending
	// SortOther sorts them in an order of another kind.
	SortOther
)

type SortOrder added in v0.2.5

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
	DottedUnderline bool
	Strikethrough   bool
	// DecorationColor and DecorationThickness are those of the span's
	// underline and strikethrough, as for Element.DecorationColor.
	DecorationColor     Color
	DecorationThickness float32
	// UnderlineOffset puts the span's underline that many DIPs below the
	// baseline, or above it when negative, as for Element.UnderlineOffset;
	// zero leaves it where the text around it has it.
	UnderlineOffset 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
	// PaddingX and PaddingY pad the Background, which then hugs the
	// span's glyphs, as CSS pads an inline box: a key cap, a mention chip.
	// PaddingX, which replaces the little that Radius widens it by, also
	// takes room in the line, moving the span's glyphs in and the text
	// after them on; PaddingY only paints, over the lines above and below,
	// as the background of an inline box does on the web. Each
	// line's piece of a span that wraps gets both, and its corners, as
	// with CSS's box-decoration-break: clone.
	PaddingX, PaddingY float32
	// PaddingStart takes that much more room at the start of each line's
	// piece of the span, past PaddingX, background or not: its left in
	// left-to-right text, its right in right-to-left text. Room for an
	// icon an app draws before it, as a link's site's.
	PaddingStart  float32
	LetterSpacing float32
	// NoLetterSpacing makes a zero LetterSpacing the span's own, rather
	// than the text's around it, as CSS's letter-spacing: 0 on an inline
	// box: digits or code within tracked capitals.
	NoLetterSpacing bool
	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) and a text what
	// Element.DrawObjects draws. ObjectDescent extends the box that far
	// below the baseline, as math's subscripts and fractions go: the line
	// makes room for it.
	ObjectWidth, ObjectHeight, ObjectDescent float32
	// BaselineShift raises the span's text, or its objects, that many
	// DIPs above the baseline, or lowers it when negative, as superscripts
	// and subscripts with a smaller Size: footnote references, exponents,
	// chemical formulas. The line makes room for it, and its underline
	// and strikethrough go with it.
	BaselineShift float32
	// Shadow is the shadow the span's text casts (NewTextShadow), as
	// Element.TextShadow casts one: zero casts that of the text around it.
	Shadow TextShadow
	// contains filtered or unexported fields
}

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, DottedUnderline and Strikethrough only turn those on.

type SplitButtonParts added in v0.9.0

type SplitButtonParts struct {
	Group  Element
	Button Element
	Arrow  Element
	// contains filtered or unexported fields
}

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

func PrimarySplitButton added in v0.9.0

func PrimarySplitButton(c *Context, label string) SplitButtonParts

PrimarySplitButton creates a split button (SplitButton) in the accent color, for the main action, as PrimaryButton is.

func SplitButton added in v0.9.0

func SplitButton(c *Context, label string) SplitButtonParts

SplitButton creates a button joined to an arrow that opens a menu of related actions, as Save beside Save As…: one control drawn as Button is, with the face and the border its two segments share and a line between them, each lighting up apart as the pointer hovers and presses it. Button, its leading segment, shows label and does the action; give Arrow, its trailing segment, the menu with Menu, or with PopoverMenuButton for one MyGo draws in the window, which opens below the arrow as a menu button's does:

save := ui.SplitButton(c, "Save")
save.Arrow.Menu(func(m *ui.Menu) {
	if m.Item("Save As…").Chosen() {
		app.saveAs()
	}
})
if save.Button.Clicked() {
	app.save()
}

It is one stop of Tab, and Left and Right move the focus between its segments, the other way round right to left, where the arrow is on the left. Enter and Space click Button while it has the focus, and open the menu while Arrow has it, as do Up and Down; Alt+Down opens it from Button too. Assistive technology sees a group of a button and a menu button, named More options until Arrow's Label names it, expanded while its menu shows. Disabled on Group disables the whole control, and on Button the action alone, leaving the menu. In a toolbar it takes no face of its own until hovered, as the toolbar's buttons. PrimarySplitButton is one in the accent color.

type SpringOptions added in v0.4.3

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.

func (SpringOptions) Progress added in v0.9.1

func (o SpringOptions) Progress(t time.Duration) float64

Progress returns where a spring of o going from 0 to 1 is after t: 0 at its start, past 1 where it overshoots, 1 once it rests. It follows the trajectory of the values Spring and AnimateTo move, for values that time sets rather than a target, as a video's frames do (plugins/render). Velocity is the value's at the start, in units of the distance a second.

func (SpringOptions) SettleTime added in v0.9.1

func (o SpringOptions) SettleTime() time.Duration

SettleTime returns how long a spring of o going from 0 to 1 takes to come to rest, where the values Spring moves stop: within Precision of 1, and as slow as that, to the millisecond, at most a minute.

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 added in v0.2.5

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, past the tabs disabled; 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. Disabled leaves it out of the keys' way and of the pointer's, and assistive technology sees it disabled.

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 NewTesterWith added in v0.8.0

func NewTesterWith(view func(c *Context), width int, height int, o TesterOptions) *Tester

NewTesterWith starts testing view in a window of width×height DIPs, as NewTester does, with the desktop's settings of o from the first frame:

tt := ui.NewTesterWith(view, 400, 300, ui.TesterOptions{Preferences: ui.Preferences{ReduceMotion: true}})

func (*Tester) Access added in v0.8.0

func (t *Tester) Access(name string) (AccessInfo, bool)

Access returns what assistive technology sees of the first element of the last frame, in the order screen readers read them, whose accessible name is name: its Label, or the text it shows. The tree is the one screen readers would get, whether or not one reads the window, and reading it changes nothing.

func (*Tester) AccessAll added in v0.9.0

func (t *Tester) AccessAll() []AccessInfo

AccessAll returns what assistive technology sees of every element of the last frame, in the order screen readers read them, as Access gives each: to check what a whole view tells screen readers, as that every control has a name.

for _, a := range tt.AccessAll() {
	if a.Role == ui.RoleButton && a.Name == "" {
		t.Errorf("a button at %v has no name", a.Bounds)
	}
}

func (*Tester) AccessByRole added in v0.8.0

func (t *Tester) AccessByRole(r Role, name string) (AccessInfo, bool)

AccessByRole returns what assistive technology sees of the first element of the last frame with role r and the accessible name name, as Testing Library's getByRole(role, {name}) finds it; "" for name finds the first element of the role whatever its name.

func (*Tester) Advance added in v0.5.5

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) Alerts added in v0.9.0

func (t *Tester) Alerts() []string

Alerts returns what a screen reader reads at once, interrupting, in order, and forgets it: the text of an ARIA alert (RoleAlert) as it appears and whenever it changes. It is empty unless UseScreenReader is on.

func (*Tester) Announcements added in v0.2.5

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. Once UseScreenReader is on it returns what a screen reader reads politely, in order: those announcements, and the text of an ARIA status (RoleStatus) when it changes and of what is added to a log (RoleLog), each once.

func (*Tester) CancelPress added in v0.8.0

func (t *Tester) CancelPress()

CancelPress has the system take the pointer's press, as a browser's pointercancel does: every button held goes up without a release, which clicks nothing (InputEvent.Canceled, PressCanceled).

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 without sending input when no element shows s, it has no visible area, or its center would reach another control or nothing.

func (*Tester) ClickAt

func (t *Tester) ClickAt(x, y float32)

ClickAt clicks at (x, y), in DIPs.

func (*Tester) ClickAtWith added in v0.2.5

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 added in v0.2.5

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. It checks the target before sending input, as Click does.

func (*Tester) Clipboard

func (t *Tester) Clipboard() string

Clipboard returns the text the view copied; SetClipboard sets the text it pastes.

func (*Tester) ClipboardData added in v0.5.0

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) CodeDown added in v0.8.0

func (t *Tester) CodeDown(mods Modifiers, code KeyCode)

CodeDown presses a key that only its position names, as a modifier on its own or Caps Lock (InputEvent.Code): mods are the modifiers held with it, its own among them.

func (*Tester) CodeUp added in v0.8.0

func (t *Tester) CodeUp(mods Modifiers, code KeyCode)

CodeUp lets go of a key CodeDown pressed: mods are the modifiers still held.

func (*Tester) Command added in v0.2.4

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 added in v0.2.4

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. Keys pressed meanwhile without Ctrl or Super go to the input method, as each platform's filter of input methods has them, and the composition stays. 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.6.0

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) FailClipboard added in v0.8.0

func (t *Tester) FailClipboard(err error)

FailClipboard makes the view's writes of text to the clipboard from now on fail with err, copying nothing, as a browser refuses them without the user acting (Context.WriteClipboardThen); nil lets them through again.

func (*Tester) FailOpenURL added in v0.2.13

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, in the window's DIPs: zoomed (SetZoom), z times the content'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 added in v0.5.5

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 added in v0.2.17

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 added in v0.4.3

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 added in v0.4.7

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) KeyRepeat added in v0.8.0

func (t *Tester) KeyRepeat(mods Modifiers, key Key)

KeyRepeat presses a key with modifiers as its auto-repeat does while it is held down (InputEvent.Repeat, Context.ShortcutRepeated).

func (*Tester) KeyUp added in v0.4.7

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: the system's, or one drawn in the window (PopoverMenu, SetMenuPresentation).

func (*Tester) Move

func (t *Tester) Move(x, y float32)

Move moves the pointer to (x, y).

func (*Tester) Now added in v0.5.5

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.6.2

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) PressButton added in v0.8.0

func (t *Tester) PressButton(button int, x, y float32)

PressButton presses (x, y) with the pointer's button, 0 the primary, 1 the secondary and 2 the middle, without releasing, as a right-button drag begins; ReleaseButton releases it.

func (*Tester) Release

func (t *Tester) Release(x, y float32)

Release releases the pointer at (x, y).

func (*Tester) ReleaseButton added in v0.8.0

func (t *Tester) ReleaseButton(button int, x, y float32)

ReleaseButton releases the pointer's button 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. It checks the target before sending input, as Click does. On an element without a context menu of its own, as a list's row, it opens the menu of the content the element holds there.

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 added in v0.5.0

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 added in v0.5.0

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 added in v0.2.4

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 added in v0.5.0

func (t *Tester) SetLocale(tag string)

SetLocale makes tag the language the app shows, as mygo.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 added in v0.2.5

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 added in v0.5.0

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 added in v0.3.4

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) SetWindowActive added in v0.8.0

func (t *Tester) SetWindowActive(active bool)

SetWindowActive draws the window as active, the window the user's input goes to, or not, as when the user switches to another window or app: Context.WindowActive returns it. It leaves the keyboard focus to SetFocused, as a window's flyout taking the keyboard leaves the window active.

func (*Tester) SetWindowHidden added in v0.8.0

func (t *Tester) SetWindowHidden(hidden bool)

SetWindowHidden hides all of the window from sight, as minimizing it or covering it with other windows does, or shows it again: Context.WindowHidden returns it, and what moves waits while it is hidden.

func (*Tester) SetZoom added in v0.7.0

func (t *Tester) SetZoom(z float32)

SetZoom zooms the content by z, as the view's Context.SetZoom does. The Tester's coordinates stay the window's: Find, ClickAt, Move, Scroll and TextCaret are in its DIPs, the view's z times smaller.

func (*Tester) TextCaret added in v0.2.4

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 added in v0.5.0

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) TouchCancel added in v0.9.2

func (t *Tester) TouchCancel(id uint64)

TouchCancel has the system take the finger id, as for a gesture of its own at the screen's edge (TouchCanceled).

func (*Tester) TouchDown added in v0.9.2

func (t *Tester) TouchDown(id uint64, x, y float32)

TouchDown puts the finger id down at (x, y) on the touchscreen, which TouchMove moves and TouchUp lifts, as a window's fingers come to the views that follow them (Element.Touches). It sends only the touch: the tap, scroll or pinch a backend makes of fingers comes from Press, Scroll and Pinch. The window gives the finger an ID of its own (Touch.ID); id may be used again once the finger lifts, as a platform's are.

func (*Tester) TouchMove added in v0.9.2

func (t *Tester) TouchMove(id uint64, x, y float32)

TouchMove moves the finger id, down since TouchDown, to (x, y).

func (*Tester) TouchUp added in v0.9.2

func (t *Tester) TouchUp(id uint64, x, y float32)

TouchUp lifts the finger id at (x, y).

func (*Tester) Type

func (t *Tester) Type(s string)

Type types text into the focused text input.

func (*Tester) TypeKey added in v0.2.4

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) UsePointer added in v0.8.0

func (t *Tester) UsePointer(pointer PointerType, pressure float32)

UsePointer has the pointer's presses and moves from now on come from the device pointer pressing with pressure, from 0 to 1, as a pen's, which a system tells: 0 is a mouse's, which tells none. The Tester starts with UsePointer(PointerMouse, 0). Calling it between moves while the pointer presses changes the pressure as a pen pressing harder does:

tt.UsePointer(ui.PointerPen, 0.2)
tt.Press(10, 10)
tt.UsePointer(ui.PointerPen, 0.9)
tt.Move(10, 10) // the pen presses harder where it stands

func (*Tester) UseScreenReader added in v0.9.0

func (t *Tester) UseScreenReader()

UseScreenReader turns assistive technology on, as a screen reader attaching to the window: from then on every frame's accessibility tree goes to it, and live regions read out what changes after it is on, as ARIA's do (a status, a log, an alert); what showed before is not read. Announcements and Alerts return what it would read.

func (*Tester) WebViewAt added in v0.4.0

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 added in v0.6.0

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 TesterOptions added in v0.8.0

type TesterOptions struct {
	// Preferences are the desktop's settings that controls follow
	// (SetPreferences).
	Preferences Preferences
	// Dark starts in the dark appearance (SetDark).
	Dark bool
}

TesterOptions are settings of the desktop that a Tester starts with, which its first frame follows, as Media Queries 5 has the user's preferences apply from the first time styles resolve: a view mounted under ReduceMotion starts no animation in its first frames either, as it would before a SetPreferences after NewTester.

type TextAffinity added in v0.2.17

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 added in v0.2.17

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 added in v0.2.17

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 added in v0.2.17

func (b *TextBuffer) ByteLen() int

func (*TextBuffer) Len added in v0.2.17

func (b *TextBuffer) Len() int

func (*TextBuffer) LineCount added in v0.2.17

func (b *TextBuffer) LineCount() int

func (*TextBuffer) Replace added in v0.2.17

func (b *TextBuffer) Replace(start, end int, s string)

Replace replaces a half-open rune range, clamping it to the document.

func (*TextBuffer) ReplaceUTF16 added in v0.2.17

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 added in v0.2.17

func (b *TextBuffer) Restore(s TextSnapshot)

Restore adopts a snapshot in constant time and advances the version.

func (*TextBuffer) RuneOffset added in v0.2.17

func (b *TextBuffer) RuneOffset(index int) int

func (*TextBuffer) Set added in v0.2.17

func (b *TextBuffer) Set(s string)

Set replaces the document. Existing snapshots retain their own version.

func (*TextBuffer) Slice added in v0.2.17

func (b *TextBuffer) Slice(start, end int) string

func (*TextBuffer) Snapshot added in v0.2.17

func (b *TextBuffer) Snapshot() TextSnapshot

func (*TextBuffer) String added in v0.2.17

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 added in v0.2.17

func (b *TextBuffer) TextForRange(r TextInputRange) (string, TextInputRange)

func (*TextBuffer) UTF16Len added in v0.2.17

func (b *TextBuffer) UTF16Len() int

func (*TextBuffer) UTF16Offset added in v0.2.17

func (b *TextBuffer) UTF16Offset(index int) int

func (*TextBuffer) Version added in v0.2.17

func (b *TextBuffer) Version() uint64

func (*TextBuffer) WriteTo added in v0.2.17

func (b *TextBuffer) WriteTo(w io.Writer) (int64, error)

type TextCaretPosition added in v0.2.17

type TextCaretPosition struct {
	Index    int
	Affinity TextAffinity
}

TextCaretPosition retains a UTF-16 index and its visual affinity.

type TextInputClient added in v0.2.17

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 added in v0.2.17

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 added in v0.2.17

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 added in v0.5.0

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 added in v0.5.0

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 added in v0.5.0

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 added in v0.2.17

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 added in v0.2.17

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 added in v0.5.0

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 added in v0.2.17

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 added in v0.2.17

func (t *TextLayout) Caret(index int) Rect

Caret gives the caret rectangle at index, snapped to a whole grapheme.

func (*TextLayout) CaretAt added in v0.2.17

func (t *TextLayout) CaretAt(p TextCaretPosition) Rect

CaretAt returns the rectangle of the requested visual edge.

func (*TextLayout) IndexAt added in v0.2.17

func (t *TextLayout) IndexAt(point Point) int

IndexAt finds the nearest whole-grapheme caret in visual layout order.

func (*TextLayout) Lines added in v0.7.2

func (t *TextLayout) Lines() []TextLine

Lines returns the lines of the layout, from the top: where a page ends, which line holds an offset, or how many lines fit a height.

func (*TextLayout) MoveCaret added in v0.2.17

func (t *TextLayout) MoveCaret(p TextCaretPosition, direction int) TextCaretPosition

MoveCaret moves one visual grapheme left (negative) or right (positive).

func (*TextLayout) NextBoundary added in v0.2.17

func (t *TextLayout) NextBoundary(index int) int

func (*TextLayout) Objects added in v0.5.0

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 added in v0.2.17

func (t *TextLayout) PositionAt(point Point) TextCaretPosition

PositionAt retains affinity while hit-testing whole graphemes.

func (*TextLayout) PreviousBoundary added in v0.2.17

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 added in v0.2.17

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 added in v0.2.17

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 added in v0.2.17

func (t *TextLayout) Size() (float32, float32)

Size is the layout's extent in DIPs.

type TextLine added in v0.7.2

type TextLine struct {
	// Rect is the line's box: X includes the alignment and the indent,
	// and W the whitespace ending the line, which the layout keeps.
	Rect Rect
	// Baseline is the y of the line's baseline; Ascent and Descent how
	// far its fonts and objects reach above and below it.
	Baseline, Ascent, Descent float32
	// Start and End are the offsets of the text the line holds: a newline
	// ending it is not included, and End is the next line's Start when the
	// line wraps.
	Start, End int
	// RTL reports a line of a paragraph reading right to left.
	RTL bool
}

TextLine is a line of a TextLayout, in DIPs from the layout's top-left corner and in UTF-16 offsets, as its other methods take them.

type TextLines added in v0.3.7

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 added in v0.3.7

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 added in v0.3.7

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 added in v0.3.7

func (l *TextLines) Count() int

Count returns how many lines the text has.

func (*TextLines) Height added in v0.3.7

func (l *TextLines) Height() float32

Height returns the height of the text: the top of the line after the last.

func (*TextLines) Rows added in v0.3.7

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 added in v0.3.7

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 added in v0.5.0

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, ObjectDescent of it below, or as far off it as its span's BaselineShift.

type TextRange added in v0.2.17

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 TextShadow added in v0.8.0

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

TextShadow is a shadow that text casts, as CSS's text-shadow, which NewTextShadow makes. The zero TextShadow casts none.

func NewTextShadow added in v0.8.0

func NewTextShadow(x, y, blur float32, c Color) TextShadow

NewTextShadow returns the shadow of the shapes of glyphs, offset by x and y DIPs and blurred by blur, in c, for a Span's Shadow:

ui.Span{Text: "Sale", Shadow: ui.NewTextShadow(0, 2, 3, t.Accent)}

Text casts the shadows that are made, so that apps that make none do not link their painting.

type TextShape added in v0.5.0

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
	// Justify stretches every line Width wraps to Width, but the last of
	// each paragraph, by widening the spaces between its words and the
	// room after Han characters and kana, as printed prose sets them.
	// Align places the last lines, and those with nothing to widen, as a
	// word broken across lines. The whitespace ending a line hangs past
	// Width.
	Justify bool
	// Indent moves the first line of the text this many DIPs in from the
	// side its paragraph starts at, the left or the right, and wraps it
	// that much narrower, as CSS's text-indent: a book indents its
	// paragraphs so. The lines after a newline are not indented.
	Indent float32
	// NoBreakWords breaks lines only between words: a word wider than
	// Width overflows it instead of breaking.
	NoBreakWords bool
	// Balance wraps each paragraph in lines of about the same length, at
	// the narrowest width that keeps them as many as Width wraps, as
	// Text's Balance does.
	Balance bool
	// Pretty keeps the last line of each paragraph from holding a single
	// word, as Text's Pretty does.
	Pretty bool
}

TextShape is how ShapeRichTextWith lays text out.

type TextSnapshot added in v0.2.17

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 added in v0.2.17

func (s TextSnapshot) ByteLen() int

func (TextSnapshot) Len added in v0.2.17

func (s TextSnapshot) Len() int

func (TextSnapshot) Line added in v0.2.17

func (s TextSnapshot) Line(line int) string

func (TextSnapshot) LineAt added in v0.2.17

func (s TextSnapshot) LineAt(index int) int

func (TextSnapshot) LineCount added in v0.2.17

func (s TextSnapshot) LineCount() int

func (TextSnapshot) LineRange added in v0.2.17

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 added in v0.2.17

func (s TextSnapshot) RuneOffset(index int) int

func (TextSnapshot) Slice added in v0.2.17

func (s TextSnapshot) Slice(start, end int) string

func (TextSnapshot) String added in v0.2.17

func (s TextSnapshot) String() string

func (TextSnapshot) TextForRange added in v0.2.17

func (s TextSnapshot) TextForRange(r TextInputRange) (string, TextInputRange)

func (TextSnapshot) UTF16Len added in v0.2.17

func (s TextSnapshot) UTF16Len() int

func (TextSnapshot) UTF16Offset added in v0.2.17

func (s TextSnapshot) UTF16Offset(index int) int

func (TextSnapshot) Version added in v0.2.17

func (s TextSnapshot) Version() uint64

func (TextSnapshot) WriteTo added in v0.2.17

func (s TextSnapshot) WriteTo(w io.Writer) (int64, error)

type Theme

type Theme struct {
	Dark bool
	// DisableAutoDimming keeps disabled elements at full opacity. Applications
	// opting in must provide their own disabled colors; input, focus and
	// accessibility still use the element's disabled state.
	DisableAutoDimming bool
	// 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 controls.
	Border 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
	// InactiveAccent is what the accent fades to in a window that is not
	// drawn as active (Context.WindowActive), as AppKit fades an inactive
	// window's: the fill of selected rows, of checked check boxes, radio
	// buttons and switches, of sliders and progress bars, the line of the
	// selected tab and the icons of a sidebar, with AccentText on it as on
	// the accent; primary buttons show as the others there. Left zero, it
	// is a gray AccentText stands out on; set it to Accent to keep the
	// accent in every window.
	InactiveAccent 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,
	// FocusRingWidth DIPs wide (2 by default; 0 is 2) and FocusRingOffset
	// DIPs outside its edge (1 in LightTheme and DarkTheme): 0 puts the
	// ring on the edge, and a negative offset inside it.
	// Element.FocusRingOffset and Element.FocusRingColor change them for
	// one element.
	Focus           Color
	FocusRingWidth  float32
	FocusRingOffset float32
	// 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): the defaults of ScrollbarStyle, which overrides
	// them where it sets a field. It styles their tracks, hover and drag
	// colors, the width of their bars and thumbs, their corners and
	// shortest thumb; a theme that sets neither draws as it always has.
	Scrollbar      Color
	ScrollbarWidth float32
	ScrollbarStyle ScrollbarStyle
	// 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
	// TooltipDelay is how long the pointer rests on an element before its
	// tooltip shows (Tooltip, TooltipBase): 0 is 0.6 seconds, and a
	// negative delay shows it at once. Within two thirds of it after
	// another tip goes, as the pointer moves along a toolbar, the next one
	// shows at once: 0.4 seconds by default.
	TooltipDelay time.Duration
	// contains filtered or unexported fields
}

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 theme for a light appearance.

func (*Theme) Rem added in v0.2.1

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 added in v0.2.1

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)).

func (*Theme) WithAccent added in v0.9.0

func (t *Theme) WithAccent(a Color) *Theme

WithAccent returns a copy of the theme in the accent a, as the default theme takes the desktop's: AccentHover, AccentPressed, Selection and Focus are shades of a for the theme's appearance, lighter in the dark, and AccentText is white, or near black on an accent as light as yellow. a is made opaque; with an A of 0 the copy keeps the theme's accent, as where the desktop has none. A theme of the app's can take the desktop's accent this way:

c.SetTheme(ui.DarkTheme().WithAccent(c.Preferences().Accent))

func (*Theme) WithPreferences added in v0.9.0

func (t *Theme) WithPreferences(p Preferences) *Theme

WithPreferences returns a copy of the theme that follows the desktop's settings p as the default theme does: in p's accent (WithAccent), with borders and secondary text stronger and the focus ring opaque under HighContrast, and FontSize TextScale times larger. A theme that already follows them, as the default theme (Context.Theme) and those WithPreferences returns do, follows p in their place: what they changed goes back first, and what was set since stays.

t := *c.Theme()
t.Background = ui.Hex("#18181b")
c.SetTheme(t.WithPreferences(c.Preferences()))

type Timeline added in v0.5.0

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 MyGo: 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 added in v0.5.0

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 added in v0.5.0

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 added in v0.5.0

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 added in v0.5.0

func (t *Timeline) Progress() float32

Progress is how far the playhead is along the timeline, from 0 to 1.

func (*Timeline) Settled added in v0.5.0

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 added in v0.5.0

func (t *Timeline) Time() time.Duration

Time is where the playhead is, from the start of the timeline.

func (*Timeline) Tween added in v0.5.0

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 added in v0.5.0

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
	// NonMotion says that the timeline's tweens move nothing on screen,
	// as fades and blurs: it still plays while the desktop asks for less
	// motion, as Animation's NonMotion does. Give what moves a timeline
	// of its own, which goes to rest at once.
	NonMotion bool
}

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, Bottom 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, and end Bottom below the top edge: on macOS the bottom edge of the traffic lights, and Height on Linux and Windows, where the controls fill the band.

type Toast added in v0.2.15

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 or the keyboard focus is in them, and runs on while the
	// window is in the background or hidden: a toast whose time is over by
	// the time the window shows again closes before it shows.
	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 added in v0.2.15

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

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

func ToastBase added in v0.2.15

func ToastBase(c *Context, t Toast) ToastParts

ToastBase creates the toast t without a look, in the viewport of ToastViewportBase.

func (ToastParts) ActionButton added in v0.2.15

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 added in v0.2.15

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 added in v0.2.15

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 Touch added in v0.9.2

type Touch struct {
	// ID tells the finger apart from the others for as long as it
	// touches, from TouchBegan to TouchEnded or TouchCanceled; the window
	// gives no other finger the same ID.
	ID uint64
	// X and Y are where the finger is, and StartX and StartY where it
	// landed, relative to the element's box.
	X, Y           float32
	StartX, StartY float32
	// Phase is what the finger did since the last build.
	Phase TouchPhase
	// Pressure is how hard the finger presses, from 0 to 1, where the
	// system tells it, else 0.5 while it touches, as Pointer Events'.
	Pressure float32
	// Width and Height are the size of the finger's contact with the
	// screen, in the element's units (DIPs), where the system tells it,
	// else 0: a palm presses a larger area than a fingertip. Windows and
	// browsers tell it where the touchscreen does; Linux does not.
	Width, Height float32
}

Touch is a finger on a touchscreen, on an element that asks about its fingers (Element.Touches).

type TouchPhase added in v0.9.2

type TouchPhase uint8

TouchPhase is what a finger did since the last build (Touch.Phase).

const (
	// TouchBegan is a finger that landed since the last build, and may
	// have moved since.
	TouchBegan TouchPhase = iota
	// TouchMoved is a finger that moved since the last build.
	TouchMoved
	// TouchStationary is a finger that stayed where it was.
	TouchStationary
	// TouchEnded is a finger that lifted since the last build, at X, Y:
	// the last build to see it. A finger that lands and lifts before a
	// build comes as TouchBegan in one build and TouchEnded in the next, so
	// that a view counting the fingers that land sees each one.
	TouchEnded
	// TouchCanceled is a finger the system took since the last build, as
	// for a gesture of its own at the screen's edge: no completed gesture,
	// and the last build to see it.
	TouchCanceled
)

Phases of a touch.

type Track added in v0.2.1

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

Track sizes a column or a row of a grid: Fixed, Fr or FitContent, and with Min or MinContent a least size.

func FitContent added in v0.2.1

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 added in v0.2.1

func Fixed(v float32) Track

Fixed is a track of v DIPs.

func Fr added in v0.2.1

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. Min and MinContent give it a least size.

func (Track) Min added in v0.8.0

func (t Track) Min(v float32) Track

Min makes the track no smaller than v DIPs, as CSS's minmax(<v>px, …): a main pane beside a side column that keeps a readable width, the grid overflowing its box rather than squeezing it.

ui.Grid(c).ColumnTracks(ui.Fr(1).Min(240), ui.Fixed(320))

An Fr track whose share of the room would be less is sized by its minimum, and the other Fr tracks share the rest, as CSS finds the size of an fr.

func (Track) MinContent added in v0.8.0

func (t Track) MinContent() Track

MinContent makes an Fr track no smaller than the content of the items in it, their min-content widths (or heights, for a row), as CSS's minmax(auto, <f>fr), the automatic minimum CSS's plain 1fr has: a label's column that takes the room left but never cuts the label. Items spanning several tracks widen the MinContent Fr tracks among them, in proportion to their shares. Other tracks are unchanged by it.

type Transform added in v0.4.3

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 TranslationZ, Translation3D, 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 added in v0.4.3

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 added in v0.4.3

func Rotation(degrees float32) Transform

Rotation rotates clockwise by degrees in the window's coordinate system.

func RotationX added in v0.4.3

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 added in v0.4.3

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 added in v0.4.3

func Scaling(x, y float32) Transform

Scaling scales each axis; zero collapses it and negative values reflect it.

func Skewing added in v0.4.3

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 added in v0.4.3

func Translation(x, y float32) Transform

Translation moves content by x and y DIPs.

func Translation3D added in v0.8.0

func Translation3D(x, y, z float32) Transform

Translation3D moves content by x and y DIPs in its plane and z toward the viewer, as CSS's translate3d(): Translation and TranslationZ.

func TranslationZ added in v0.8.0

func TranslationZ(z float32) Transform

TranslationZ moves content z DIPs along the axis toward the viewer, as CSS's translateZ(): with Perspective after it, nearer for positive z, looking larger, and farther for negative z, looking smaller, by distance/(distance-z) around the transform's origin. Without Perspective it changes nothing that shows, as in CSS. Content moved as far as Perspective's distance, or past it, is behind the viewer and shows nothing.

// 120 DIPs behind the plane, seen from 800 DIPs: 800/920 its size.
ui.Box(c).Size(240, 160).Transform(ui.TranslationZ(-120).Then(ui.Perspective(800)))

func (Transform) Then added in v0.4.3

func (t Transform) Then(next Transform) Transform

Then applies t first, then next.

type Transition added in v0.2.5

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
	// TransitionMatch fades the page going out as the page coming fades
	// in, while the elements of a Transition's Match in both move from
	// the one to the other, as Keynote's Magic Move: a photo's thumbnail
	// opening into its page, its title growing into the page's heading.
	// Where the desktop asks for less motion, nothing moves.
	TransitionMatch
)

type TreeItemParts added in v0.8.0

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

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

func (TreeItemParts) Depth added in v0.8.0

func (_handle TreeItemParts) Depth() int

Depth returns how deep the item is: 0 at the top, 1 inside an item at the top, and so on, to indent its row by.

func (TreeItemParts) Group added in v0.8.0

func (_handle TreeItemParts) Group(fn func()) Element

Group builds the items inside the item, which fn makes with the tree's Item, while it is open, in a column below the item's row. It returns the column, to style, as with a line along it, and nil while the item is closed or a leaf.

type TreeParts added in v0.8.0

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

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

func TreeBase added in v0.8.0

func TreeBase(c *Context) TreeParts

TreeBase creates a tree without a look, as the web's role="tree": a column of items that Item makes, each a row the caller styles and fills, built inside the item it belongs to with Group. The tree is one stop of Tab, which goes to the item that had the focus last, or the one Selected; while an item has the focus, Up and Down move it to the items around, Home and End to the first and the last, Right opens the item or moves to its first child, Left closes it or moves to its parent (the other way round right to left), and typing the first letters of an item moves to it. Build the items in Root:

tree := ui.TreeBase(c)
tree.Root.Gap(2).Children(func() {
	var node func(n *Node)
	node = func(n *Node) {
		c.Key(n.path) // the focus follows it as items above open
		item := tree.Item(n.open) // nil for a leaf
		item.Row.Gap(4).Padding(4, 8).PaddingStart(8 + 16*float32(item.Depth())).Radius(6)
		if item.Row.FocusVisible() {
			item.Row.Background(gray)
		}
		item.Row.Children(func() {
			arrow := ui.Box(c).Size(16, 16)
			if n.open != nil && arrow.Clicked() {
				*n.open = !*n.open
			}
			ui.Text(c, n.name)
		})
		item.Group(func() {
			for _, k := range n.children {
				node(k)
			}
		})
	}
	for _, n := range app.roots {
		node(n)
	}
})

Tree is TreeBase with the theme's look. TreeBase builds every item that shows; for trees of thousands of items, use Outline, which builds only the rows in view, with a Prefix of your own.

func (TreeParts) Item added in v0.8.0

func (_handle TreeParts) Item(open *bool) TreeItemParts

Item creates an item of the tree, at the top or, inside Group, in the item that Group is of. With a nil open it is a leaf; otherwise the items Group builds inside it show while *open is true, which Right and Left set, as does assistive technology. A key given with Context.Key just before keeps its focus on it, and on the items inside it, as items above open and close.

type Tween added in v0.5.0

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.

type VideoDecoder added in v0.7.2

type VideoDecoder interface {
	// Next decodes the next frame, with io.EOF after the last.
	Next() (VideoFrame, error)
	// Rewind goes back to before the first frame, for the video to play
	// again.
	Rewind() error
}

A VideoDecoder decodes a video's frames one after another, for a VideoPlayer to show. NewGIFDecoder and NewAPNGDecoder return one for animated GIFs and PNGs; implement one for another format. A player calls it from one goroutine at a time. A decoder that also has a method Duration() time.Duration reports the video's length through the player's Duration.

func NewAPNGDecoder added in v0.9.0

func NewAPNGDecoder(data []byte) (VideoDecoder, error)

NewAPNGDecoder returns a decoder of an animated PNG's frames, for NewVideoPlayer, as browsers show them: a frame of 10 ms or less shows for 100 ms. A PNG that is not animated is a video of one frame. Each frame is kept compressed, and decoded as it plays. The player's SetLoop, not the PNG's count of plays, says whether it plays again.

func NewGIFDecoder added in v0.7.2

func NewGIFDecoder(data []byte) (VideoDecoder, error)

NewGIFDecoder returns a decoder of an animated GIF's frames, for NewVideoPlayer, as browsers show them: a frame of 10 ms or less shows for 100 ms. The GIF decodes into memory at once, its frames' pixels a byte each, and each frame is drawn as it plays. The player's SetLoop, not the GIF's loop count, says whether it plays again.

type VideoFrame added in v0.7.2

type VideoFrame struct {
	// Image is the picture, of any image type: the player converts it as
	// Bitmap.Update does, and copies it, so the decoder may draw the next
	// frame into it.
	Image image.Image
	// Duration is how long the frame shows; a frame of none shows for
	// 100 ms, as browsers show GIFs'.
	Duration time.Duration
}

A VideoFrame is a picture of a video and how long it shows.

type VideoPlayer added in v0.7.2

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

A VideoPlayer plays a video, for Video to show. NewVideoPlayer makes one of a VideoDecoder's frames, which MyGo decodes in Go; package ui/video opens files and streams with the system's own media framework, which decodes them on the GPU and plays their sound.

A decoder's frames decode on a goroutine of their own a few ahead, as the playhead nears them, and each reaches the screen through a Bitmap's Update as it comes due, a frame passed over when the next one is due already. A system's frames stay where its decoder left them, on the GPU, and the window's renderer draws them from there.

A new player plays as soon as a Video shows it; show it in one Video at a time. Call its methods on the main thread, in the view or an input handler, as drawing does.

func NewEngineVideoPlayer added in v0.9.0

func NewEngineVideoPlayer(e media.Engine) *VideoPlayer

NewEngineVideoPlayer returns a player of a video that e, an engine of the system's media framework, plays: package ui/video's Open makes them. The player holds the engine paused until a Video shows it, then plays it, unless paused.

It is exported for ui/video only, as media is internal: apps open videos with ui/video.

func NewVideoPlayer added in v0.7.2

func NewVideoPlayer(d VideoDecoder) (*VideoPlayer, error)

NewVideoPlayer returns a player of d's frames, playing. It decodes the first frame at once, which Video shows from its first frame, and which reports a video that does not decode. Make players once, not in the view, as bitmaps. Closing the player closes d if d is an io.Closer.

func (*VideoPlayer) Buffering added in v0.9.0

func (p *VideoPlayer) Buffering() bool

Buffering reports whether a stream waits for data it downloads, as a player shows a spinner for.

func (*VideoPlayer) Close added in v0.7.2

func (p *VideoPlayer) Close()

Close stops decoding, and closes the decoder if it is an io.Closer, on a goroutine of its own once the frame it may be decoding is done; or stops the system's player, and its sound. The video shows the frame it was at.

func (*VideoPlayer) Duration added in v0.9.0

func (p *VideoPlayer) Duration() time.Duration

Duration returns the length of the video: 0 while unknown, as for a live stream, or a decoder that does not report it.

func (*VideoPlayer) Ended added in v0.9.0

func (p *VideoPlayer) Ended() bool

Ended reports whether the video played to its end, and stands at its last frame; Play plays it again.

func (*VideoPlayer) Err added in v0.7.2

func (p *VideoPlayer) Err() error

Err returns what stopped the video before its end, as a frame that did not decode or a stream that broke off: the video shows the frame before it.

func (*VideoPlayer) Loop added in v0.7.2

func (p *VideoPlayer) Loop() bool

Loop reports whether the video plays again as it ends.

func (*VideoPlayer) Muted added in v0.9.0

func (p *VideoPlayer) Muted() bool

Muted reports whether the video's sound is silenced (SetMuted).

func (*VideoPlayer) Pause added in v0.7.2

func (p *VideoPlayer) Pause()

Pause holds the video at the frame it shows.

func (*VideoPlayer) Play added in v0.7.2

func (p *VideoPlayer) Play()

Play goes on from where the video was paused, or plays it again from its start once it ended.

func (*VideoPlayer) Playing added in v0.7.2

func (p *VideoPlayer) Playing() bool

Playing reports whether the video plays: neither paused nor ended. It plays while out of sight too, though it does not move on then.

func (*VideoPlayer) Position added in v0.9.0

func (p *VideoPlayer) Position() time.Duration

Position returns the time of the video the player shows.

func (*VideoPlayer) Rate added in v0.9.0

func (p *VideoPlayer) Rate() float64

Rate returns how fast the video plays (SetRate).

func (*VideoPlayer) Ready added in v0.9.0

func (p *VideoPlayer) Ready() bool

Ready reports whether the video has a picture to show: always for a decoder's, and for one the system opens once it loaded its first.

func (*VideoPlayer) Seek added in v0.9.0

func (p *VideoPlayer) Seek(d time.Duration)

Seek shows the video at d, from its start, and goes on playing from there unless paused: the frame of a decoder's video showing at d, which it decodes from the start up to it.

func (*VideoPlayer) SetLoop added in v0.7.2

func (p *VideoPlayer) SetLoop(loop bool) *VideoPlayer

SetLoop plays the video again from its start each time it ends, without a gap. It returns the player.

func (*VideoPlayer) SetMuted added in v0.9.0

func (p *VideoPlayer) SetMuted(m bool) *VideoPlayer

SetMuted silences the video's sound, or plays it again. A muted video is a picture only, as a background is: it pauses while out of sight, and shows its first frame while the desktop asks for less motion, rather than play. It returns the player.

func (*VideoPlayer) SetRate added in v0.9.0

func (p *VideoPlayer) SetRate(r float64) *VideoPlayer

SetRate plays the video r times as fast, keeping the pitch of its sound: 0.5 at half speed, 2 at double. It returns the player.

func (*VideoPlayer) SetVolume added in v0.9.0

func (p *VideoPlayer) SetVolume(v float64) *VideoPlayer

SetVolume sets the volume of the video's sound, from 0 to 1, the full volume, as it is from the start. A decoder's video has no sound. It returns the player.

func (*VideoPlayer) Size added in v0.7.2

func (p *VideoPlayer) Size() (w, h int)

Size returns the size of the video's frames in pixels, which Video shows as DIPs: 0×0 until the video is Ready.

func (*VideoPlayer) Volume added in v0.9.0

func (p *VideoPlayer) Volume() float64

Volume returns the volume of the video's sound (SetVolume).

type VideoSeeker added in v0.9.1

type VideoSeeker interface {
	VideoDecoder
	// Seek goes to the frame showing at d from the start, or the last
	// one when d is past the end, which Next decodes next, and returns
	// when that frame starts.
	Seek(d time.Duration) (time.Duration, error)
}

A VideoSeeker is a VideoDecoder that goes to any time of its video at once, rather than decoding every frame before it: a player seeking takes it, where it would decode the frames from the start.

type YUVFormat added in v0.9.0

type YUVFormat uint8

YUVFormat is how a YUVImage lays out its samples.

const (
	// NV12 is a plane of luma and one of chroma, Cb and Cr interleaved, as
	// hardware decoders leave pictures (VideoToolbox, Direct3D, VA-API).
	NV12 YUVFormat = iota
	// I420 is a plane of luma, one of Cb and one of Cr, as software
	// decoders leave pictures (FFmpeg's YUV420P).
	I420
)

type YUVImage added in v0.9.0

type YUVImage struct {
	// Format is how the planes hold the samples.
	Format YUVFormat
	// Width and Height are the picture's size in pixels. Its chroma is
	// half as wide and high, rounded up.
	Width, Height int
	// Planes are the luma, a byte a pixel, then NV12's chroma, Cb and Cr
	// interleaved, a pair of bytes for each sample, or I420's Cb and Cr,
	// a byte each. Strides are their rows' lengths in bytes, which may be
	// longer than the samples, as decoders pad them.
	Planes  [3][]byte
	Strides [3]int
	// Matrix converts the samples to RGB, and FullRange tells that they
	// take all of 0 to 255 rather than video's range, 16 to 235 for luma
	// and 16 to 240 for chroma, as JPEG's do and video's rarely do.
	Matrix    YUVMatrix
	FullRange bool
}

A YUVImage is a picture in Y′CbCr with its chroma at half the size both ways (4:2:0), as video decoders give their frames, for a bitmap to show without converting it to RGBA (Bitmap.UpdateYUV).

type YUVMatrix added in v0.9.0

type YUVMatrix uint8

YUVMatrix is the standard whose coefficients convert Y′CbCr to RGB.

const (
	// BT601 is standard definition video's, and JPEG's.
	BT601 YUVMatrix = iota
	// BT709 is HD video's, as most streams, cameras and screen
	// recordings are.
	BT709
	// BT2020 is UHD video's. Only its matrix applies: HDR video shows with
	// the transfer of SDR.
	BT2020
)

Source Files

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 MyGo's native UI, on package ui.
Package editor is a code editor and a diff viewer for MyGo'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.
Package video plays video files and streams with the system's own media framework, for ui.Video to show: AVFoundation on macOS, Media Foundation on Windows, GStreamer on Linux and the video element in browsers.
Package video plays video files and streams with the system's own media framework, for ui.Video to show: AVFoundation on macOS, Media Foundation on Windows, GStreamer on Linux and the video element in browsers.

Jump to

Keyboard shortcuts

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