ui

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 45 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. Changed and Submitted apply pending input to controls built so far before returning, so local bound values can be committed in the same build pass. Click and shortcut queries also apply pending bound input before returning, so inline actions see the latest edits on controls already built. Configure input options before querying responses. Remaining bound input applies after construction. OnClick, OnShortcut, OnChange and OnSubmit run after construction and bound input, before the rebuild. Input queries such as Clicked remain available.

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

Tester runs views in tests, without a window.

Index

Constants

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

Keys.

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

Modifier keys.

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

Pointer shapes.

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

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

Variables

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

func Overlay

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

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

func RegisterFont

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

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

func Render

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

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

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

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
)

Anchors, from left to right and top to bottom.

type Bitmap

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

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

func DecodeBitmap

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

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

func NewBitmap

func NewBitmap(img image.Image) *Bitmap

NewBitmap converts img.

func (*Bitmap) 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.

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

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. It applies pending input to the controls built so far, 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. It returns the panel, or nil while closed or without options.

func (ComboboxParts) SetOpen added in v0.2.5

func (_handle ComboboxParts) SetOpen(o bool)

SetOpen opens or closes the popup.

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

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

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.

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

func (c *Context) Services() Services

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

func (*Context) SetTheme

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

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

func (*Context) Shortcut

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

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

func (*Context) Size

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

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

func (*Context) Theme

func (_handle *Context) Theme() *Theme

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

func (*Context) TitleBar

func (_handle *Context) TitleBar() TitleBar

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

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

func (_handle *Context) WriteClipboard(s string)

type Cursor

type Cursor uint8

Cursor is a pointer shape.

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.

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 group; name it with Label.

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

func Button

func Button(c *Context, label string) Element

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

func ButtonBase

func ButtonBase(c *Context) Element

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

func Calendar 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: a click chooses a day, as the arrows do while the calendar has the focus, Page Up and Page Down or its buttons move by months, and Home and End go to the first and the last day of the month. Changed reports a new date, which keeps the time of day and location of *date. Assistive technology reads the day chosen as the arrows move.

func Checkbox

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

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

func CheckboxBase

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

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

func CheckboxGroup 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 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. 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 as 2006-01-02, which a calendar below it changes. A click, Enter or Space opens the calendar, where a click chooses a day, as do the arrows and Enter; Page Up and Page Down, or its buttons, move by months, and Escape closes it. Changed reports a new date, which keeps the time of day and location of *date.

func DialogBase

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

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

func Divider

func Divider(c *Context) Element

Divider creates a thin line across its row or column.

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

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. Assistive technology sees a level indicator of that value; name it with Label.

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

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

func NumberInput

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

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

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

func Outline 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, so trees of any size are as fast as small ones. With s.List.Selected or Selection, rows are chosen as a List's, and while the outline has the focus, Right opens the item chosen or goes to its first child, and Left closes it or goes to its parent, with Option on macOS and Shift elsewhere, as in GTK, opening and closing all inside.

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

func OutlineTable 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. 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 to the right of the anchor:

panel.AttachTo(anchor, ui.AnchorRight, ui.AnchorLeft).Margin(0, 0, 0, 6)

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

func PrimaryButton

func PrimaryButton(c *Context, label string) Element

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

func Progress

func Progress(c *Context, value float64) Element

Progress creates a progress bar filled to value between 0 and 1; a negative value shows activity of unknown length. Reverse fills it from the right, for interfaces laid out from right to left.

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

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:

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. 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. Changed reports a move.

ui.Split(c, &app.sidebar, 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 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; 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.

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 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, as 15:04, whose hours and minutes 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, and Left and Right move between them. Changed reports a new time, which keeps the date and the location of *tm. Assistive technology sees two spin buttons, named after the field's Label and "hours" and "minutes".

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, the keyboard focus is in it, or the window is in the background. viewport stays while no toast shows, for the last one to go with an exit transition. It returns viewport.

func Toggle 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.

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. It goes as the pointer leaves anchor or presses it, and with Escape, until the pointer comes back or the focus does. Over elements inside one another, the innermost one's tip shows; one shows at a time.

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

ui.TooltipBase(c, b, func(tip ui.Element) {
	tip.AttachTo(b, ui.AnchorRight, ui.AnchorLeft).Margin(0, 0, 0, 6)
	tip.Padding(4, 8).Radius(6).Background(dark).TextColor(light)
	tip.Children(func() { ui.Text(c, "Share") })
})

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

func Tree

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

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

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

func TreeItem

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

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

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

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

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

func (_handle Element) Background(c Color) Element

Background fills the element, in place of a gradient.

func (Element) Basis

func (_handle Element) Basis(v float32) Element

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

func (Element) BasisPercent 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) 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) 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 element's box in the previous frame, in DIPs relative to the window; it is empty for an element the previous frame lacked.

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 applies pending input to the controls built so far and reports whether this widget's value changed in this build pass. Configure controls before querying their response; the bound value is updated before returning.

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. Bases set it from their value.

func (Element) Children

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

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

func (Element) ClickModifiers 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) 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) 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.

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

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

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

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

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

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

func (Element) 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) 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) Disabled

func (_handle Element) Disabled(d bool) Element

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

func (Element) Dismissed 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) 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) 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) Dragged

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

Dragged reports how far the pointer moved since the last frame while pressing the element.

func (Element) Dragging added in v0.2.5

func (_handle Element) Dragging() bool

Dragging reports whether the element is dragging its value (Drag).

func (Element) Draw

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

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

func (Element) DrawOver

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

DrawOver paints on the element with p after its children.

func (Element) DroppedFiles

func (_handle Element) DroppedFiles() []string

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

func (Element) 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) 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) 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) 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() Element

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

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), and on out of it; the arrows that o names move it among them, round from the last to the first, and Home and End to the first and the last. An element inside that takes those keys itself, as a slider or a text input does, keeps them. Groups inside a group are part of it.

func (Element) FocusRing

func (_handle Element) FocusRing(show bool) Element

FocusRing sets whether 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) FocusVisible

func (_handle Element) FocusVisible() bool

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

func (Element) FocusWithin

func (_handle Element) FocusWithin() bool

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

func (Element) Focusable

func (_handle Element) Focusable() Element

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

func (Element) Focused

func (_handle Element) Focused() bool

Focused reports whether the element has the keyboard focus.

func (Element) Font

func (_handle Element) Font(family string) Element

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

func (Element) FontFeatures

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

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

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

A font without a feature ignores it.

func (Element) FontSize

func (_handle Element) FontSize(v float32) Element

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

func (Element) FontWeight

func (_handle Element) FontWeight(w int) Element

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

func (Element) Gap

func (_handle Element) Gap(v float32) Element

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

func (Element) GapX 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 or scrolling 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; 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) Height

func (_handle Element) Height(v float32) Element

Height sets the height in DIPs.

func (Element) HeightPercent

func (_handle Element) HeightPercent(p float32) Element

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

func (Element) Highlighted

func (_handle Element) Highlighted() bool

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

func (Element) Hovered

func (_handle Element) Hovered() bool

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

func (Element) ID

func (_handle Element) ID() uint64

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

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

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

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

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.

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) 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) 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 the app reads from the clipboard itself. fn reports whether it took the paste; a paste taken changes nothing, its selection and undo history included, as when a web page prevents a paste's default and attaches a large block instead of inserting it. Like ReadOnly, it holds for the input that comes until the next frame.

func (Element) OnShortcut 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) Opacity

func (_handle Element) Opacity(o float32) Element

Opacity makes the element and its children translucent.

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

func (_handle Element) Placeholder(s string) Element

Placeholder shows s in an empty text input.

func (Element) PointerPosition

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

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

func (Element) Pressed

func (_handle Element) Pressed() bool

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

func (Element) PressedOutside 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.

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.

func (Element) Ref added in v0.3.0

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

Ref is an alias for Bind.

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

func (_handle Element) Rotate(degrees float32) Element

Rotate turns an Icon by degrees clockwise around its center, as a spinner does:

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

func (Element) Row

func (_handle Element) Row() Element

Row lays the children out from left to right.

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.

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) ScrollIntoView added in v0.2.3

func (_handle Element) ScrollIntoView() Element

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

func (Element) ScrollWith 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) 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) 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) 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) 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) 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) 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) 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 applies pending input to the controls built so far and reports whether Enter was pressed in a single-line text input. Configure controls before querying their response; the bound value is updated before returning.

func (Element) TextAlign

func (_handle Element) TextAlign(a Align) Element

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

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, with ranges that do not overlap. 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) 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) 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) 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, and nothing does while the desktop asks for less motion (Preferences.ReduceMotion).

func (Element) Underline

func (_handle Element) Underline() Element

Underline underlines text.

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.

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

type ElementTransition added in v0.2.8

type ElementTransition struct {
	// Duration is how long a change takes: 200 ms when zero.
	Duration time.Duration
	// Ease is how the element goes, as for AnimateWith: EaseOut when nil.
	Ease Easing
	// Position, Size and Colors choose what animates: where the element is
	// in its parent, its width and height (its content laid out at each
	// size on the way), and its background and border colors. None set
	// animates them all.
	Position, Size, Colors bool
	// Enter, if set, is where the element comes from as it appears in a
	// parent that the last frame showed: it starts there, and goes to its
	// place.
	Enter *Motion
	// Exit, if set, is where the element goes once it is no longer built,
	// while its parent still is: a copy of it, as the last frame showed
	// it, goes there under its siblings, taking neither room, the pointer
	// nor the focus, and is then gone.
	Exit *Motion
}

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

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

type Fit

type Fit uint8

Fit says how an image fills its element.

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

type Font added in v0.2.4

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

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

func (Font) Metrics added in v0.2.4

func (f Font) Metrics() FontMetrics

Metrics returns the font's metrics.

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

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.

type ImageSource

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

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

type InputEvent added in v0.2.4

type InputEvent struct {
	Kind   InputKind
	Key    Key
	Mods   Modifiers
	Repeat bool
	// Text of InputText, InputCompose and InputCommand, and Caret the
	// rune of an InputCompose's caret.
	Text  string
	Caret int
	// X and Y locate the pointer relative to the element's box.
	X, Y float32
	// Button is 0 for the primary button, 1 the secondary and 2 the
	// middle.
	Button int
	Clicks int
	// DX and DY are what InputScroll scrolls by; positive DY moves the view
	// down the content.
	DX, DY  float32
	Precise bool
}

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).
	InputKeyDown InputKind = iota + 1
	InputKeyUp
	// InputText is text typed, or committed by an input method.
	InputText
	// InputCompose is the composition of an input method, with its caret
	// at rune Caret; an empty Text ends it.
	InputCompose
	// InputCommand is an edit command of the menus, such as Copy of the
	// Edit menu: "copy", "cut", "paste", "selectAll", "undo", "redo" or
	// "delete".
	InputCommand
	// InputPointerDown and InputPointerUp report Button pressed or
	// released at X, Y, with Clicks the count of quick successive presses
	// (2 for a double click). Once the element takes an InputPointerDown,
	// the pointer's moves and its release come to it wherever they are,
	// and the release comes when the window loses the keyboard too.
	InputPointerDown
	InputPointerUp
	// InputPointerMove reports the pointer at X, Y, with Button held, or
	// -1 when none is.
	InputPointerMove
	// InputScroll scrolls by DX, DY DIPs at X, Y; Precise marks
	// touchpads, which scroll by pixels rather than by lines.
	InputScroll
)

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

LinearGradient blends two colors along a line across a box, as CSS's linear-gradient does with two colors:

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.

func (ListRow) ListFocused added in v0.3.0

func (r ListRow) ListFocused() bool

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
	// FollowEnd starts the list at its end, and keeps the end in view as
	// rows are added or grow while it shows it, as a chat or a log does:
	// scrolling away from the end stops following it, and scrolling back
	// to it follows again.
	FollowEnd bool
	// Selected, when set, lets a click choose a row, as Up, Down, Home and
	// End do while the list has the keyboard focus, and Page Up and Page
	// Down on Linux and Windows: *Selected is the chosen row, -1 for none,
	// which shows in the accent color. The list's Changed reports a new
	// choice, and its Submitted a double click or Enter.
	Selected *int
	// Selection, when set, lets the user choose several rows, which it
	// holds by their keys: a click chooses one, Cmd-click (Ctrl-click on
	// Linux and Windows) adds a row or takes it out, and Shift-click
	// chooses those from the row last chosen to it, as Shift with the keys
	// that move the choice does; Cmd+A chooses all. On Linux and Windows,
	// Ctrl with those keys moves without choosing, and Ctrl+Space adds the
	// row there or takes it out. Selected, set as well, is the row last
	// chosen, where the keys move from.
	Selection Selector
	// 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)
	// 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.
	Sort *SortOrder
	// Columns keeps the order and the widths the user gave a Table's
	// columns, by ID: restore it from saved settings, and save it as it
	// changes.
	Columns TableLayout
	// RoundRows rounds the corners of a Table's chosen and hovered rows at
	// the theme's Radius, as a List's are, rather than leaving them square
	// from edge to edge.
	RoundRows bool
	// 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) 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) 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) 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 list nearing the end of what was loaded, say, loads more. A frame that changes them builds another, for what read them.

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 or Element.Menu. Its items show in the order they are added.

func (m *Menu) EditItems()

EditItems adds the editing items of the text the menu opened on, as its menu has them without ContextMenu: Copy and Select All for selectable text, the platform's text field items for a text input. Choosing one does its command on the text, without reaching the menu's function. It adds nothing to a menu that opened on no text.

func (m *Menu) Item(label string) *MenuItem

Item adds an item showing label.

func (m *Menu) Separator()

Separator adds a line between groups of items.

func (m *Menu) Submenu(label string, build func(m *Menu)) *MenuItem

Submenu adds an item showing label that opens a submenu, which build fills as ContextMenu's function fills the menu.

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

MenuItem is an item of a Menu. Its methods set it up and return it, for chaining, and Chosen reports the choice.

func (it *MenuItem) Checked(on bool) *MenuItem

Checked shows a check mark by the item when on is true, as for a setting that choosing the item toggles.

func (it *MenuItem) Chosen() bool

Chosen reports whether the item was chosen, in the frame after the user chose it.

func (it *MenuItem) Disabled(d bool) *MenuItem

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

func (it *MenuItem) Shortcut(mods Modifiers, key Key) *MenuItem

Shortcut shows a key with modifiers by the item, as the shortcut that does the same; the view handles the key itself, as with Context.Shortcut.

type MeterLevels added in v0.2.5

type MeterLevels struct {
	Warning, Critical float64
}

MeterLevels are the levels of a Meter from which its value shows it is worse: the theme's Warning color from Warning, its Danger color from Critical. A Critical below Warning makes low values the bad ones, as a battery's. Their zero value shows the theme's Success color throughout.

type Modifiers

type Modifiers uint8

Modifiers are modifier keys.

type Motion added in v0.2.8

type Motion struct {
	// X and Y move it by as many DIPs.
	X, Y float32
	// Opacity is how opaque it is there: 0, as by default, is
	// transparent, and 1 opaque.
	Opacity float32
	// Collapse makes it nothing along its parent's direction: no height in
	// a column, no width in a row. Its content keeps its layout, clipped.
	Collapse bool
}

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

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 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]
	// 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) 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) Clip

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

Clip restricts what fn draws to r.

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

func (p *Painter) Fill(r Rect, c Color, radius float32)

Fill paints a rounded rectangle.

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 (non-zero winding).

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

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

FocusRing draws the ring that shows the keyboard focus around r.

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

func (p *Painter) Line(x0, y0, x1, y1, width float32, c Color)

Line paints a straight horizontal or vertical line between two points, width DIPs thick.

func (*Painter) MeasureText 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) 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) 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) 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 round joins and caps.

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) 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) Theme added in v0.2.10

func (p *Painter) Theme() *Theme

Theme returns the theme of the view being painted.

type Path

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

Path is a vector shape, in DIPs, for Painter.FillPath and StrokePath: icons, check marks, charts.

func (*Path) Circle

func (p *Path) Circle(cx, cy, r float32) *Path

Circle adds a circle as a subpath.

func (*Path) Close

func (p *Path) Close() *Path

Close closes the subpath.

func (*Path) CubeTo

func (p *Path) CubeTo(c1x, c1y, c2x, c2y, x, y float32) *Path

CubeTo draws a cubic Bézier curve to (x, y) with control points (c1x, c1y) and (c2x, c2y).

func (*Path) LineTo

func (p *Path) LineTo(x, y float32) *Path

LineTo draws a line to (x, y).

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float32) *Path

MoveTo starts a new subpath at (x, y).

func (*Path) QuadTo

func (p *Path) QuadTo(cx, cy, x, y float32) *Path

QuadTo draws a quadratic Bézier curve to (x, y) with control point (cx, cy).

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 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
	// HighContrast asks for more contrast: macOS's Increase Contrast,
	// Windows's contrast themes, the desktop portal's higher contrast. The
	// default theme then draws borders and secondary text darker (lighter
	// in the dark), and the focus ring opaque.
	HighContrast bool
	// TextScale is how many times larger than usual text should be, as
	// Windows's and GNOME's text size settings say, 1 for usual: the
	// default theme's FontSize is that much larger.
	TextScale float32
}

Preferences are settings of the desktop that the system's own controls follow. The default theme follows them, and Animate follows ReduceMotion; a theme of your own (Context.SetTheme) and drawing of your own may read them with Context.Preferences.

type Rect

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

Rect is a rectangle in DIPs.

func (Rect) Contains

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

Contains reports whether the point is inside r.

type Ref 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
	RoleCheckBox
	RoleRadio
	RoleSwitch
	RoleSlider
	RoleProgress
	RoleTextField
	RoleImage
	RoleList
	RoleScroll
	RoleDialog
	RolePopup
	RoleTooltip
	RolePopUpButton
	RoleTabList
	RoleTab
	RoleSplitter
	RoleStatus
	RoleTable
	RoleRow
	RoleCell
	RoleColumnHeader
	RoleTree
	RoleTreeItem
	// RoleListItem is an item of a list: the rows of a List are.
	RoleListItem
	// RoleMenuButton is a button opening a menu (Element.Menu).
	RoleMenuButton
	// RoleToolbar holds controls (Toolbar), RoleRadioGroup radio buttons
	// (RadioGroup, Segmented), and RoleToggleButton is a button that stays
	// pressed (Toggle).
	RoleToolbar
	RoleRadioGroup
	RoleToggleButton
	// RoleComboBox is a text input with a popup of options (ComboboxBase).
	RoleComboBox
	// RoleDisclosure is a button showing or hiding content below it, as
	// the trigger of a collapsible (CollapsibleBase), expanded while open.
	RoleDisclosure
	// RoleMeter shows a value in a range (Meter), and RoleStepper steps a
	// value in one (Stepper).
	RoleMeter
	RoleStepper
	// RoleColorWell is a button showing a color, which it opens a picker
	// of (ColorWell).
	RoleColorWell
	// RoleAlertDialog is a dialog asking about something important
	// (AlertDialog).
	RoleAlertDialog
	// RoleMenu holds the items of a menu drawn in the window, as a drop-down
	// menu's panel, and RoleMenuBar the titles of menus along it.
	// RoleMenuItem is an item of either, and RoleMenuItemCheckBox and
	// RoleMenuItemRadio items showing a choice, checked with Checked.
	RoleMenu
	RoleMenuBar
	RoleMenuItem
	RoleMenuItemCheckBox
	RoleMenuItemRadio
	// RoleHeading is the title of a section, named by its text, its rank
	// set with Level.
	RoleHeading
)

type Route 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.
	Transition Transition
	// 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).

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 and style sheets of simple selectors. It leaves out text, embedded images, patterns, markers and filters: convert text to paths before.

func MustParseSVG

func MustParseSVG(data []byte) *SVG

MustParseSVG is ParseSVG for SVGs that are part of the program, such as embedded files: it panics when one is in error.

func ParseSVG

func ParseSVG(data []byte) (*SVG, error)

ParseSVG parses an SVG document.

func (*SVG) Size

func (s *SVG) Size() (w, h float32)

Size returns the size the SVG says it has, its width and height or those of its viewBox, which Image shows as DIPs.

type ScrollState added in v0.2.3

type ScrollState struct {
	Handle

	// X and Y are how far the content is scrolled left and up, in DIPs.
	// 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
}

ScrollState is how far a scroll container scrolls its content, kept in the app's state with TrackScroll.

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, Enter and Space choose one, and Escape closes it; the trigger's Changed reports a new choice. Give the trigger children showing the choice, and build the options in Popup with Item:

sel := ui.SelectBase(c, &app.size)
sel.Trigger.Padding(6, 10).Border(1, gray).Children(func() {
	ui.Text(c, app.size)
})
sel.Popup(func(panel ui.Element) {
	panel.Padding(4).Background(white).Border(1, gray)
	for _, size := range sizes {
		item := sel.Item(size).Padding(6, 10)
		if item.Highlighted() {
			item.Background(blue).TextColor(white)
		}
		item.Children(func() { ui.Text(c, size) })
	}
})

Select is SelectBase with the theme's look.

func (SelectParts[T]) Highlight 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, as a select of your own may do as the user types the option's first letters; Enter then chooses it.

func (SelectParts[T]) Item

func (_handle SelectParts[T]) Item(value T) Element

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

func (SelectParts[T]) Open

func (_handle SelectParts[T]) Open() bool

Open reports whether the popup shows.

func (SelectParts[T]) Popup

func (_handle SelectParts[T]) Popup(fn func(panel Element)) Element

Popup shows the popup below the trigger, at least as wide, while it is open: fn styles the panel and builds the options in it with Item. Clicking outside it or pressing Escape closes it. It returns the panel, or nil when the popup is closed.

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

func (s Services) WriteClipboard(text string)

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
	Strikethrough bool
	// DecorationColor and DecorationThickness are those of the span's
	// underline and strikethrough, as for Element.DecorationColor.
	DecorationColor     Color
	DecorationThickness float32
	// Background highlights the span, as search results are.
	Background    Color
	LetterSpacing float32
	Features      string // as for Element.FontFeatures, comma separated
}

Span is a run of a RichText with a style of its own. What it leaves zero takes the style of the text around it, and Italic, Underline, WavyUnderline and Strikethrough only turn those on.

type 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): 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.
	Sortable bool
	// Fixed keeps the column where it is and as wide as it is: the user
	// neither moves nor resizes it.
	Fixed 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; List's Changed reports a new choice. Build the tabs in List with Tab:

tabs := ui.TabsBase(c, &app.tab, len(names))
tabs.List.Gap(4).Children(func() {
	for i, name := range names {
		tab := tabs.Tab(i).Padding(6, 12).Radius(6)
		if i == app.tab {
			tab.Background(c.Theme().Surface)
		}
		tab.Children(func() { ui.Text(c, name) })
	}
})

Tabs is TabsBase with the theme's look.

func (TabsParts) Tab

func (_handle TabsParts) Tab(i int) Element

Tab creates tab i of the list: a row that takes the focus and chooses i when clicked. Style it from whether i is the one chosen.

type Tester

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

Tester runs a view without a window, as a test drives it: it renders frames in memory and sends the view pointer and keyboard input, between which it settles the frames the view asks for.

func NewTester

func NewTester(view func(c *Context), width int, height int) *Tester

NewTester starts testing view in a window of width×height DIPs. Two elements given one key under one parent make it panic where the second was given, as apps only log it.

func (*Tester) 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.

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.

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.

func (*Tester) Clipboard

func (t *Tester) Clipboard() string

Clipboard returns the text the view copied; SetClipboard sets the text it pastes.

func (*Tester) CloseMenu

func (t *Tester) CloseMenu()

CloseMenu closes the context menu shown without choosing an item.

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", "selectAll", "undo", "redo" or "delete".

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.

func (*Tester) Cursor

func (t *Tester) Cursor() Cursor

Cursor returns the pointer shape the view shows.

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.

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

func (t *Tester) Menu() []string

Menu returns the labels of the items of the context menu shown, "-" for separators, or nil when none is.

func (*Tester) Move

func (t *Tester) Move(x, y float32)

Move moves the pointer to (x, y).

func (*Tester) OpenedURLs

func (t *Tester) OpenedURLs() []string

OpenedURLs returns the links the view opened.

func (*Tester) Press

func (t *Tester) Press(x, y float32)

Press presses (x, y) without releasing; Release releases it.

func (*Tester) Release

func (t *Tester) Release(x, y float32)

Release releases the pointer at (x, y).

func (*Tester) RightClick

func (t *Tester) RightClick(s string) error

RightClick clicks the center of the element showing text or labeled s with the secondary button.

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

func (*Tester) SetClipboard

func (t *Tester) SetClipboard(s string)

SetClipboard sets the clipboard's text.

func (*Tester) SetDark

func (t *Tester) SetDark(dark bool)

SetDark switches between the light and the dark appearance.

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

func (*Tester) Texts

func (t *Tester) Texts() []string

Texts returns the texts of the last frame, in order.

func (*Tester) Type

func (t *Tester) Type(s string)

Type types text into the focused text input.

func (*Tester) TypeKey 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) 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.

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 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 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) 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) 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 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 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 and, when Weight is set, their weight, as a message field shows the mentions in what is typed.

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
	// 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
	Danger        Color
	// Warning and Success color what calls for attention and what went
	// well, as a Meter's levels.
	Warning Color
	Success Color
	// Selection highlights selected text.
	Selection Color
	// Focus is the ring around the control with the keyboard focus.
	Focus Color
	// Inverse fills tooltips and toasts, the theme turned over so that
	// they stand out from what they are over: dark in a light theme, light
	// in a dark one. InverseText is text on it. Left zero, they are Text
	// and Background.
	Inverse     Color
	InverseText Color
	// Scrollbar colors scroll bar thumbs, ScrollbarWidth DIPs wide (6 by
	// default; 0 is 6).
	Scrollbar      Color
	ScrollbarWidth float32
	// Radius rounds the corners of controls.
	Radius float32
	// Spacing is the unit of the room widgets leave inside and between
	// their parts: their paddings and gaps, and the sizes of check boxes,
	// switches, sliders and the rows of tables and trees, are multiples
	// of it. 4 by default: 3 makes widgets compact, 5 roomy; 0 is 4.
	Spacing float32
	// FontSize is the size of text, Font its family ("" is the system's).
	FontSize float32
	Font     string
}

Theme holds the colors and metrics widgets use. Change a copy of LightTheme or DarkTheme and set it with Context.SetTheme.

func DarkTheme

func DarkTheme() *Theme

DarkTheme returns the theme for a dark appearance.

func LightTheme

func LightTheme() *Theme

LightTheme returns the 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)).

type TitleBar

type TitleBar struct{ Height, Left, Right float32 }

TitleBar is the room the window controls take at the top of a window with a hidden title bar, in DIPs: they sit in a band of Height along the top edge, Left wide from the left edge and Right wide from the right.

type Toast 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, the keyboard focus is in them, or the window is in the
	// background.
	Timeout time.Duration
	// Action labels a button that runs OnAction, as Undo after deleting,
	// and closes the toast.
	Action   string
	OnAction func()
	// OnClose runs as the toast closes: its time is over, or the user, its
	// action or CloseToast closed it.
	OnClose func()
	// Data holds what else the look of the toast needs.
	Data any
}

Toast is a toast that AddToast shows, and that the view builds with ToastViewportBase to give toasts a look of its own.

type ToastParts 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.AnimationContext to draw it moving.

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.

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.

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
)

Jump to

Keyboard shortcuts

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