base

package
v1.0.31-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 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 base provides the shared runtime every element package is built on: the Element interface, the frame and color helpers, the absolute-position, portal, semantic and Back/OnKey registries, and the keyed and memo caches. Element packages import it; users of the library import the elements facade instead.

Index

Constants

View Source
const CompactWidth = 600

CompactWidth is the window width, in dp, under which Compact reports true outside any Responsive.

View Source
const DefaultRetainFrames = 60

DefaultRetainFrames is how many frames an entry may go unrequested before it's dropped. Frames only happen when something changes, so this is not a fixed time.

View Source
const Unbounded = 1e6

Unbounded mirrors the sentinel Gio uses for infinite constraints.

Variables

View Source
var (
	SelectionLen     = func() int { return -1 }
	SelectionReorder = func(spans [][2]int) {}
)

SelectionLen is how many text parts the innermost selection area holds so far this frame, -1 outside one; SelectionReorder rearranges them: spans, ranges of parts, in the order they're to take. The text package sets both.

View Source
var InSelectionArea = func() bool { return false }

InSelectionArea reports whether a SelectionArea is being laid out; the text package sets it.

View Source
var SelectionVersion = func() uint64 { return 0 }

SelectionVersion reports the version of the innermost selection area's selection, for caches inside it to notice a change. The selection element sets it from its init; it reports 0 outside any selection area.

Functions

func AbsolutePosition

func AbsolutePosition() image.Point

AbsolutePosition returns the accumulated offset at the current point in the Layout traversal: where the calling element's origin currently sits relative to the window. Only meaningful while being laid out as part of the current frame.

While a child of a Row or Stack with several children is being laid out, it returns the container's origin rather than the child's: a flex container measures every child before it knows where any of them land. What the child registers with that position - portals (RegisterPortal), semantic nodes, positions tracked with TrackPosition - is moved to the child's real position once the container places it (see ChildTracker), so a dropdown opened from the second field of a row still opens below that field. Code that stores the position for later should use TrackPosition, which stays exact, rather than keep the value returned here.

func ActiveBreakpoint

func ActiveBreakpoint() string

ActiveBreakpoint returns the Name of the breakpoint the innermost enclosing Responsive matched, or "" outside any Responsive (or when the matched breakpoint has no name). Only meaningful while being laid out as part of the current frame.

func AddSticky

func AddSticky(it *StickyItem) bool

AddSticky hands it to the innermost scope, and reports whether there was one: without one, the element paints itself in the flow.

func AfterLayout

func AfterLayout(fn func())

AfterLayout runs fn once the current frame's layout is finished, on the UI goroutine, then requests another frame. A handler that must change the model the rest of this frame is still reading - removing the list item being laid out, say - defers the change with it. Called outside a frame, fn runs after the next one.

func BeginFrame

func BeginFrame()

BeginFrame starts a new frame. The app calls it before laying out the view; component authors don't need to.

func BeginSemantics

func BeginSemantics()

BeginSemantics starts recording the semantic tree for a frame. The app calls it when semantics are enabled (the MCP server enables them); component authors don't need to.

func ClearPortals

func ClearPortals()

ClearPortals drops every queued portal.

func Compact

func Compact() bool

Compact reports whether the innermost enclosing Responsive matched a breakpoint named "compact" - the conventional name for a phone layout. Outside any Responsive, it reports whether the window is narrower than CompactWidth.

func ContextClaimed

func ContextClaimed(e pointer.Event) bool

ContextClaimed reports whether an element opened its context menu for e, a press: a window-wide menu (App.SetContextMenu) leaves it.

func CurrentColor

func CurrentColor() string

CurrentColor returns the inherited color, or "" outside any colored container.

func Describe

func Describe(el Element) string

Describe names an element for diagnostics: its kind and the first text inside it, which is usually enough to find it in the code.

func DispatchBack

func DispatchBack(gtx layout.Context)

DispatchBack delivers this frame's Back and Escape presses to the topmost registered handler, then clears the registrations. The app calls it once per frame, after the view and portals are laid out and before RunAfterLayout; component authors don't need to.

func DispatchKeys

func DispatchKeys(gtx layout.Context)

DispatchKeys delivers the keys left over this frame to the OnKey handlers, then clears them. The app (and ui.Frame) calls it once per frame, after the portals and DispatchBack; component authors don't need to.

func DisplayScale

func DisplayScale() float32

DisplayScale returns the display's pixels per dp as of the last frame (1 on a standard display, 2 on a typical HiDPI one). It is safe to call from anywhere, including outside Layout, to convert sizes for code that doesn't have a layout context.

func DpToPx

func DpToPx(v float32) int

DpToPx converts dp to pixels with the last frame's display scale.

func DragActive

func DragActive() bool

DragActive reports whether a drag is in progress.

func DrainContextMenus

func DrainContextMenus(gtx layout.Context)

DrainContextMenus lays out the context menus that show, before the portals they draw through. The app (and ui.Frame) calls it once per frame, after the view.

func DrainPortals

func DrainPortals(gtx layout.Context)

DrainPortals lays out and paints every portal registered so far this frame, in registration order (later registrations paint on top of earlier ones), then clears the queue. The app calls this once per frame, after the rest of the view.

AbsolutePosition/PushOffset are kept in sync with the paint offset here (not just op.Offset) so that content built inside a portal - nested Menu submenus register a further portal of their own, anchored off their own row's position - reports its true screen position rather than whatever was accumulated before the portal that contains it was originally triggered.

Portals registered while draining (a submenu opened by its parent menu's row) are drained too, in the same frame.

func EndFrame

func EndFrame()

EndFrame finishes a frame, releasing keyed memos (see Memo) that weren't laid out during it. The app calls it after every frame.

func FlexPercentOf

func FlexPercentOf(el Element, axis layout.Axis) int

FlexPercentOf returns el's percentage size for axis, or 0.

func FlexWeightOf

func FlexWeightOf(el Element, axis layout.Axis) int

FlexWeightOf returns el's flex grow weight for axis, or 0.

func ForgetKeyed

func ForgetKeyed(scope, key any)

ForgetKeyed drops the state stored under (scope, key) right away.

func ForwardKey

func ForwardKey(e key.Event)

ForwardKey passes a key a component took but didn't use on to the OnKey handlers (app shortcuts) at the end of the frame, as if nothing had taken it; the component reports it with SeenKey as well.

func FrameNumber

func FrameNumber() uint64

FrameNumber returns the current frame number, which BeginFrame advances. Element packages use it for state that is reset every frame.

func GridPlacementOf

func GridPlacementOf(el Element) (col, row properties.GridSpan)

GridPlacementOf returns el's grid placement: automatic, one track, when it says none.

func HandleBack

func HandleBack(fn func())

HandleBack registers fn to run when the user presses the system Back button (Android's Back gesture or key) during this frame. Call it from Layout, every frame, for as long as there is somewhere to go back to - Router does this while its history isn't empty.

Handlers registered later in the frame win: content laid out on top (a dialog over a page) takes Back before what's beneath it, and only the topmost handler runs. When no handler is registered, giode leaves Back to the platform, which on Android closes the app.

Android asks whether Back is handled the moment it is pressed, using the handlers registered in the last frame. That's why handlers are registered from Layout rather than consulted afterwards: whether Back is consumed must be known before the press arrives.

fn runs after the current frame's layout (see AfterLayout), so it may change anything the view reads.

func HandleDismiss

func HandleDismiss(fn func())

HandleDismiss is HandleBack for overlays: fn also runs when Escape is pressed. Dialog, Drawer and Menu use it while open.

func InvalidateCaches

func InvalidateCaches()

InvalidateCaches forces every MemoCache and Memo to rebuild on the next frame. Call it after changing something caches can't observe - a plain variable not passed as a dep, a component driven programmatically (Button.Click, Input.SetText) - when the change must show up inside a cached subtree. It is safe to call from any goroutine; it doesn't request a frame by itself.

func IsCacheSafe

func IsCacheSafe(el Element) bool

IsCacheSafe reports whether el is a CacheSafe element that says it is safe to cache.

func IsUnbounded

func IsUnbounded(max int) bool

IsUnbounded reports whether a maximum constraint means "no limit". Margins and padding subtract from the sentinel on the way down, so anything above half of it counts.

func Keyed

func Keyed[T any](scope, key any, init func() T) T

Keyed returns the state stored under (scope, key), creating it with init the first time it's asked for. Use it inside the view function to give each item of a dynamic list its own stateful component:

for _, f := range files {
	row := giode.Keyed("files", f.ID, func() *giode.PressableElement {
		return giode.Pressable(...)
	})
	rows = append(rows, row)
}

scope separates unrelated lists that might share keys; any comparable values work for both. If a key was stored with a different type, init replaces it. Entries not asked for in DefaultRetainFrames frames are dropped (see SetKeyedRetention). Call it on the UI goroutine.

func MarkTyping

func MarkTyping()

MarkTyping records, for this frame, that a focused text field takes typing: the keys that type text (a character or Space, with no modifier but Shift) then don't reach OnKey handlers. Gio sends each key both as typed text, to the field, and as a key event, which the field doesn't take, so without this "H" or Space typed into a field would also run an "H" or "Space" shortcut. A text field calls it every frame it has focus; giode's Input does.

func Measure

func Measure(gtx layout.Context, el Element) layout.Dimensions

Measure lays el out without painting, taking input, registering portals, Back handlers or selectable text, or recording semantics, and returns its size - for components that must know a child's size before placing it.

func Measuring

func Measuring() bool

Measuring reports whether the element being laid out is only being measured: what it registers for the frame - selectable text, say - is dropped with its ops, so it registers nothing.

func MinTouchTarget

func MinTouchTarget(gtx layout.Context, w layout.Widget) layout.Dimensions

MinTouchTarget lays out w and, while TouchInput is on, grows the returned size to at least 48x48dp (bounded by the constraints) with w centered inside it. Wrap a control's visual in it, inside the widget that takes its clicks, so the hit area grows while the visual keeps its size:

dims := clickable.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
	return elements.MinTouchTarget(gtx, visual)
})

With a mouse it lays w out unchanged.

func NoteDragAware

func NoteDragAware()

NoteDragAware reports that the element being laid out takes part in drag and drop.

func OnKey

func OnKey(fn func(key.Event) bool, named ...NamedKey)

OnKey registers fn, for this frame, to receive the keys nothing else took: app-wide shortcuts. Call it from the view every frame, as with HandleBack.

fn sees a key only after everything else in the frame had its chance - the focused field, dialogs, menus and other portals, and the Back and Escape handlers (HandleBack, HandleDismiss) - so a shortcut never steals typing from a text field or Escape from an open dialog, whatever order the view lays things out in. While a text field has focus, the keys that type into it (a character or Space, alone or with Shift) don't reach fn at all (see MarkTyping); shortcuts with Ctrl, Cmd or Alt, function keys and Escape do. It gets presses and releases (check e.State) and returns whether it used the key. With several handlers, the one registered last asks first.

Gio gives some keys - Tab and Shift+Tab, which otherwise move the focus - only to a listener that names them. List such keys in named, each with exactly the modifiers to hold, for fn to get them; a press with other modifiers still moves the focus. Shortcuts does this for the keys its shortcuts name.

func PaintSticky

func PaintSticky(gtx layout.Context, items []*StickyItem, origin, viewport image.Point, rtl bool)

PaintSticky paints the content's sticky elements over it: each where the scrolled flow put it, or held at the top (or start) edge once scrolled past it, until the next one sticking to that edge pushes it out, as section headers do. origin is the scroll's absolute position; the items' positions are absolute, scrolled.

func PendingPortals

func PendingPortals() []portalEntry

PendingPortals returns the portals queued since the last drain, without draining them. Element packages and tests inspect the queue; callers must not keep or reorder it.

func PercentOf

func PercentOf(st styles.Styles, axis layout.Axis) int

PercentOf returns an element's percentage size for axis.

func PopBreakpoint

func PopBreakpoint()

PopBreakpoint ends the innermost PushBreakpoint.

func PushBreakpoint

func PushBreakpoint(name string)

PushBreakpoint marks name as the active breakpoint until PopBreakpoint runs. The Responsive element calls it around laying out the matching view.

func PushColor

func PushColor(c string) (pop func())

PushColor makes c the inherited color until the returned function runs. Empty colors are ignored. Custom containers that set a text color for their content call it around laying the content out.

func PushOffset

func PushOffset(off image.Point) (pop func())

PushOffset accumulates off into the tracked absolute position; pair with the op.Offset(off).Push()/Pop() around the same child. A custom element that positions its own children with op.Offset should call this alongside it so AbsolutePosition (and therefore kit.RegisterPortal) works correctly for content placed inside it.

func PushSemanticScroll

func PushSemanticScroll(target any) (pop func())

PushSemanticScroll marks the nodes recorded until pop is called as content of the scroll container target, which should then record itself as a SemanticScroll node with that Target. A scroll component calls it around laying out its content, so automation can scroll the container to reach a node:

pop := elements.PushSemanticScroll(s)
dims := s.content().Layout(cgtx)
pop()
...
elements.RecordSemantic(gtx, elements.SemanticNode{Kind: elements.SemanticScroll, Target: s}, viewport)

For automation to scroll it, target should have the methods ScrollBy(dx, dy float32) and ScrollOffset() (x, y float32), in pixels.

func PushStickyScope

func PushStickyScope(s *StickyScope) (pop func())

PushStickyScope makes s collect the sticky elements laid out until pop runs. A measure (Measure) collects none.

func PushVisibleClip

func PushVisibleClip(c *VisibleClip) (pop func())

PushVisibleClip makes c the visible area of the content laid out until pop runs. Call it at the container's own position, before laying out (and tracking) its scrolled content, and set c.Size to the viewport before the frame ends.

func PxToDp

func PxToDp(px int) float32

PxToDp converts pixels to dp with the last frame's display scale.

func RecordSemantic

func RecordSemantic(gtx layout.Context, n SemanticNode, size image.Point)

RecordSemantic adds a node to the semantic tree of the frame being laid out, a no-op unless recording. Call it from a custom component's Layout, after laying out, with the component's size:

elements.RecordSemantic(gtx, elements.SemanticNode{
	Kind: elements.SemanticButton, Label: b.label, Target: b,
}, dims.Size)

Bounds and ID are filled in when left empty.

func RecordSemanticLabeled

func RecordSemanticLabeled(gtx layout.Context, kind SemanticKind, label, value string, size image.Point)

RecordSemanticLabeled records a node without a target, skipping empty labels. Element packages use it for their routine text nodes.

func RegisterOverlay

func RegisterOverlay(build func() Element)

RegisterOverlay queues build to be laid out over the whole window, above the rest of the view, like a portal anchored at the window's origin that's neither measured nor clamped: build gets the window's size as its maximum constraints and positions its own content - a bottom sheet, a full-screen picker. Overlays and portals paint in registration order.

func RegisterPortal

func RegisterPortal(gtx layout.Context, anchor image.Point, build func() Element)

RegisterPortal queues build to be laid out and painted for real after the rest of the view - the mechanism behind Tooltip, nested Menu submenus and AutoComplete's suggestion panel, and the building block for any component that needs to render on top of everything else no matter how deeply it's nested in the tree.

anchor is a window-absolute point (typically AbsolutePosition(), optionally offset - e.g. by the trigger element's own height) that the content is positioned near; it's first laid out once on a disabled scratch context, bounded by the window (see SetWindowSize) rather than gtx's own ambient constraints, to measure its size (the same technique Menu's own panel-width measurement uses) so the position can be clamped to stay inside the window, flipping above the anchor if it would overflow the bottom edge - see kit.ClampPos. build is then laid out for real, exactly once, when the queue is drained.

The anchor follows the caller when an enclosing Row, Stack or Scroll places it after the fact (see ChildTracker), so a portal opened from one of several children of a row lands below that child, and the clamping happens once its final position is known.

func RegisterPortalAround

func RegisterPortalAround(gtx layout.Context, trigger image.Rectangle, gap int, place Placement, build func() Element)

RegisterPortalAround queues build like RegisterPortal, placed next to trigger, a window-absolute rectangle (AbsolutePosition() and the trigger's size): gap pixels below it or above it, per place. Unlike RegisterPortal's flip, which only knows a point, flipping around the rectangle never covers the trigger - a tooltip on a control bar at the bottom of the window goes above its button.

Its start edges line up with the trigger's: left edges, or right edges when gtx reads right to left.

func RegisterPortalAt

func RegisterPortalAt(gtx layout.Context, anchor image.Point, alignEnd bool, build func() Element)

RegisterPortalAt queues build like RegisterPortal at anchor, a window position that stays put: containers that place their children after laying them out don't move it, unlike RegisterPortal's anchor. For content opened at a known window position - a context menu at the pointer. With alignEnd, anchor is the content's top-right corner.

func RegisterPortalEnd

func RegisterPortalEnd(gtx layout.Context, anchor image.Point, build func() Element)

RegisterPortalEnd queues build like RegisterPortal with anchor as the content's top-right corner rather than its top-left: a menu opened at a point in a right-to-left layout extends to the left of it.

func ReorderTracked

func ReorderTracked(ts []ChildTracker)

ReorderTracked tells the innermost selection area the screen order of children a container laid out in another order - a list laying its rows out from the bottom up - so selecting by dragging runs through them top to bottom. ts are the children's trackers, in screen order.

func ResolveColor

func ResolveColor(c string) color.NRGBA

ResolveColor resolves an element's own color: c when set, otherwise the inherited color, otherwise black.

func RetainKeyed

func RetainKeyed(touch func())

RetainKeyed registers touch with the innermost recording cache. It is retainKeyed for element packages replayed by a MemoCache.

func RunAfterLayout

func RunAfterLayout() bool

RunAfterLayout runs and clears the AfterLayout queue, reporting whether anything ran. The app calls it after laying out each frame; component authors don't need to.

func SeenKey

func SeenKey(e key.Event)

SeenKey reports a key a component took, for the WatchKeys handlers. Components that take keys from Gio themselves call it; app code doesn't need to.

func SemanticsEnabled

func SemanticsEnabled() bool

SemanticsEnabled reports whether the current frame records a semantic tree. Components can skip computing labels when it doesn't.

func SemanticsWanted

func SemanticsWanted() bool

SemanticsWanted reports whether a bridge reads the tree.

func SetDebugLogger

func SetDebugLogger(fn func(format string, v ...any))

SetDebugLogger sets the function layout diagnostics go to, such as the warning about FlexGrow in an unbounded container; nil turns them off. The app sets it from Config.Logger at LogLevelDebug; component authors don't need to.

func SetDragActive

func SetDragActive(v bool)

SetDragActive records that a drag started (true) or ended (false). The dnd package calls it.

func SetKeyedRetention

func SetKeyedRetention(frames int)

SetKeyedRetention sets how many frames Keyed entries survive without being asked for (minimum 1).

func SetMetric

func SetMetric(m unit.Metric)

SetMetric records the frame's display metric. The app calls it every frame; component authors don't need to.

func SetSemanticsWanted

func SetSemanticsWanted(on bool)

SetSemanticsWanted makes the app record the semantic tree every frame (true) or only when automation asks (false). Accessibility bridges set it while a screen reader is on, from any goroutine.

func SetTouchInput

func SetTouchInput(v bool) (changed bool)

SetTouchInput records whether the last press came from a touch screen and reports whether that changed. The app calls it for every press; component authors don't need to.

func SetWindowSize

func SetWindowSize(size image.Point)

SetWindowSize records the window's size for the current frame. The app calls this once, before laying out the view; component authors calling RegisterPortal don't need to call it themselves.

func ShowMenu

func ShowMenu(m ContextMenu)

ShowMenu has m laid out every frame while it's open, wherever it was opened from, as an element's context menu is: a menu opened at a click (Menu.OpenAtClick) needs no place in the view.

func TouchInput

func TouchInput() bool

TouchInput reports whether the user is interacting by touch: always on Android and iOS until a mouse is used, and on other platforms after a touch press. Components use it to grow their touch targets (see MinTouchTarget).

func TrackPosition

func TrackPosition(p *image.Point)

TrackPosition stores the calling element's absolute position in *p and keeps it exact: when an enclosing Row, Stack or Scroll learns where it really put the element - which a flex container only knows after laying every child out - *p is shifted to match. Read *p once the frame's layout is done: in the next frame's event handling, a click handler, or a portal's build function.

prev := t.origin // exact, from the last frame
elements.TrackPosition(&t.origin)

A measuring pass (Measure) leaves *p alone: its offset isn't where the element goes, and nothing corrects it afterwards, so a measure after the real layout would leave *p wrong.

func WarnOnce

func WarnOnce(format string, v ...any)

WarnOnce logs a diagnostic the first time a given message comes up.

func WatchKeys

func WatchKeys(fn func(key.Event))

WatchKeys registers fn, for this frame, to see every key press and release the app gets, before anything acts on it: the keys nothing took, which then go on to the OnKey handlers, and the ones a focused component took (a KeyboardInput's, a button's Enter and Space, an Input's OnKeys). Call it from the view every frame, as with OnKey. fn only watches: it can't stop a key from going where it goes. It sees the modifier keys themselves (key.NameShift, NameCtrl, NameAlt, NameCommand, NameSuper) pressed and released, so it can spot a double Shift. The keys a focused text field (Input) edits with - arrows, Backspace, Delete, Enter, Home, End and its Ctrl or Cmd shortcuts - stay inside the field and aren't seen; its typed text isn't a key press either. The keys of a frame reach fn at the end of it.

func WeightOf

func WeightOf(st styles.Styles, axis layout.Axis) int

WeightOf returns an element's flex grow weight for axis.

func WindowSize

func WindowSize() image.Point

WindowSize returns the window's size for the current frame, in pixels; zero outside a frame.

func ZIndexOf

func ZIndexOf(el Element) int

ZIndexOf returns el's z-index, or 0.

Types

type CacheSafe

type CacheSafe interface {
	CacheSafe() bool
}

CacheSafe is implemented by elements whose output depends only on their own fields, which don't change after they're built (or whose changes they track themselves), on States they read, and on input they handle through input passes. A Box made only of such elements can cache its output across frames: nothing it draws can change without the cache noticing. Raw drawing functions, builder functions and unknown elements aren't: they may read any variable.

type CheckState

type CheckState uint8

CheckState is a checkable control's state.

const (
	// NotCheckable is a node that isn't checkable.
	NotCheckable CheckState = iota
	Unchecked
	Checked
	// Mixed is a checkbox for a partly selected group.
	Mixed
)

type ChildTracker

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

ChildTracker records what a child registers while it's laid out - portals, semantic nodes and tracked positions, all placed at the absolute position current when it starts - so they can be moved to where the child actually ends up. Containers that lay a child out before they know its final offset use it (giode's Row, Stack and Scroll do):

t := elements.TrackChild()
dims := child.Layout(gtx) // recorded, offset not yet known
t.End()
... // decide where the child goes
t.Place(off)            // shift what it registered by off
defer op.Offset(off).Push(gtx.Ops).Pop()
call.Add(gtx.Ops)

func TrackChild

func TrackChild() ChildTracker

TrackChild starts recording; call it right before laying the child out.

func (*ChildTracker) End

func (t *ChildTracker) End()

End stops recording; call it right after the child's Layout returns.

func (ChildTracker) Place

func (t ChildTracker) Place(off image.Point)

Place moves everything recorded by off, the child's offset from the position it was laid out at.

type ContextMenu

type ContextMenu interface {
	Element
	// OpenAtWindow opens the menu at p, in window pixels.
	OpenAtWindow(p image.Point)
	// Opened reports whether the menu shows.
	Opened() bool
}

ContextMenu is a menu an element opens at the pointer when it's right-clicked or long-pressed: a *giode.MenuElement (Menu).

type Contextual

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

Contextual gives an element a context menu: every element and component embeds it, so each has a Context method.

row := giode.Box(st, giode.Text(name))
row.Context(rowMenu)

A right-click anywhere on the element - or a long-press on a touch screen - opens the menu where the pointer is, however small the element and wherever it sits. With elements inside each other, the innermost with a menu opens its own.

func (*Contextual) AnchorContext

func (c *Contextual) AnchorContext(gtx layout.Context, size image.Point)

AnchorContext makes the element's area, size from the current offset, open its context menu. Every element calls it at the end of its Layout, outside any cache of its own; it does nothing without a menu.

func (*Contextual) Context

func (c *Contextual) Context(m ContextMenu)

Context anchors m to the element: a right-click on it, or a long-press, opens m at the pointer. Context(nil) removes it.

func (*Contextual) ContextMenu

func (c *Contextual) ContextMenu() ContextMenu

ContextMenu returns the menu Context anchored, or nil.

type Describer

type Describer interface {
	Describe() string
}

Describer names an element for diagnostics: its kind, and the first text inside it, which is usually enough to find it in the code. Elements implement it so Describe can stay independent of the concrete type.

type Element

type Element interface {
	Layout(gtx layout.Context) layout.Dimensions
}

Element is anything that can lay itself out in a frame.

func Accessible

func Accessible(el Element, fn func(n *SemanticNode)) Element

Accessible lays el out and passes each node it records to fn, to change its role or states: a text becoming a heading, a box's text a status message.

elements.Accessible(elements.Text("Settings", big), func(n *elements.SemanticNode) {
	n.Kind, n.Level = elements.SemanticHeading, 1
})

func AccessibleGroup

func AccessibleGroup(n SemanticNode, el Element) Element

AccessibleGroup lays el out as a container node n - a region, a list, a dialog, a toolbar - whose children are el's nodes.

func Memo

func Memo(key any, build func() Element, deps ...any) Element

Memo returns an element that caches build's output under key and rebuilds it only when deps, the States it reads, its constraints or the theme change, or when a widget inside asks for it - see MemoCache for the full rules. Use it inside the view function to skip rebuilding parts of the UI that didn't change:

giode.Memo("sidebar", func() giode.Element {
	return sidebar(user.Name)
}, user.Name)

key identifies the cache across frames and must be unique among the memos laid out in a frame (any comparable value: a string, an ID, a pointer). A key not laid out for a frame is released.

type ExpandState

type ExpandState uint8

ExpandState is an expandable control's state.

const (
	// NotExpandable is a node that doesn't expand.
	NotExpandable ExpandState = iota
	Collapsed
	Expanded
)

type FlexHints

type FlexHints interface {
	FlexWeight(axis layout.Axis) int
	FlexPercent(axis layout.Axis) int
	ZIndex() int
}

FlexHints marks elements that carry layout hints: how much they grow on the flex main axis, their percentage size and their z-index.

type GridHints

type GridHints interface {
	GridPlacement() (col, row properties.GridSpan)
}

GridHints marks elements that say where they go on a grid.

type KeyedCache

type KeyedCache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

KeyedCache is a typed, self-contained version of Keyed: a map of per-item state that drops entries not asked for in a while. Hold one in a stateful component:

type fileList struct {
	rows *giode.KeyedCache[string, *giode.PressableElement]
}
...
row := l.rows.Get(file.ID, func() *giode.PressableElement { ... })

Expired entries are dropped at the end of each frame. It is safe for concurrent use, though state is normally only touched on the UI goroutine.

func NewKeyedCache

func NewKeyedCache[K comparable, V any]() *KeyedCache[K, V]

NewKeyedCache returns an empty cache that keeps entries for DefaultRetainFrames unrequested frames.

func (*KeyedCache[K, V]) Delete

func (c *KeyedCache[K, V]) Delete(key K)

Delete drops the entry for key right away.

func (*KeyedCache[K, V]) Get

func (c *KeyedCache[K, V]) Get(key K, init func() V) V

Get returns the entry for key, creating it with init the first time.

func (*KeyedCache[K, V]) Len

func (c *KeyedCache[K, V]) Len() int

Len returns the number of entries.

func (*KeyedCache[K, V]) OnEvict

func (c *KeyedCache[K, V]) OnEvict(fn func(K, V)) *KeyedCache[K, V]

OnEvict sets a function called with each dropped entry, to release resources it holds. It returns c for chaining.

func (*KeyedCache[K, V]) Peek

func (c *KeyedCache[K, V]) Peek(key K) (V, bool)

Peek returns the entry for key without creating it or keeping it alive.

func (*KeyedCache[K, V]) Range

func (c *KeyedCache[K, V]) Range(fn func(K, V) bool)

Range calls fn for each entry until it returns false.

func (*KeyedCache[K, V]) Retain

func (c *KeyedCache[K, V]) Retain(frames int) *KeyedCache[K, V]

Retain sets how many frames an entry survives without being asked for (minimum 1). It returns c for chaining.

type LiveMode

type LiveMode string

LiveMode says how changes to a node are announced.

const (
	LiveOff       LiveMode = ""
	LivePolite    LiveMode = "polite"
	LiveAssertive LiveMode = "assertive"
)

type MemoCache

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

MemoCache caches the painted output of a subtree across frames, so the subtree is only rebuilt and laid out again when something it depends on changed. Everything else replays the ops recorded last time, which costs next to nothing regardless of how large the subtree is.

A cached subtree is rebuilt when any of these changed since it was recorded:

  • the deps passed to Layout (compared with ==, or reflect.DeepEqual for values that aren't comparable);
  • any State the subtree read while being built (tracked automatically);
  • the layout constraints, the display density, the active breakpoint (see ActiveBreakpoint), touch input (see TouchInput) or the locale;
  • the theme (SetMode/SetPalette);
  • a widget inside asked for it: an animation, or a change that came from outside input (see kit.MarkLive);
  • input changed a widget inside: on a replayed frame the cache runs its widgets' input passes (see kit.HandleInput) - so hovering, tapping or scrolling over it still reaches them - and lays the subtree out again only when one reports a visible change, like a hover highlight or a press. A subtree with input handling that registers no pass (see kit.OpaqueInput) is instead laid out on every frame the pointer is active over it.

Values read from plain variables (not States) must be passed as deps, or the cache won't notice them change.

Create a MemoCache once and lay it out every frame, or use Memo for a cache keyed by an identifier inside the view function. A cache laid out twice in the same frame lays the second use out uncached.

func NewMemoCache

func NewMemoCache() *MemoCache

NewMemoCache returns an empty cache.

func (*MemoCache) Invalidate

func (c *MemoCache) Invalidate()

Invalidate drops the cached output, forcing a rebuild on the next layout.

func (*MemoCache) Layout

func (c *MemoCache) Layout(gtx layout.Context, build func() Element, deps ...any) layout.Dimensions

Layout lays out build's element, or replays the cached result when nothing it depends on changed.

func (*MemoCache) LayoutOwn

func (c *MemoCache) LayoutOwn(gtx layout.Context, build func() Element, watch Watcher, deps ...any) layout.Dimensions

LayoutOwn lays a stateful component out through its own cache: the output recorded last time is replayed until something it draws changes - its own fields (label, value, styles), which watch tracks, deps (the layout context: direction, a parent's stretch), or anything a Memo watches (States read, constraints, theme, input through its passes, animations). watch is also checked when an enclosing cache replays the component without laying it out, so a setter changing a field is never missed. watch may be nil for a component whose fields don't change once built. Pass the same build function every frame, rather than a new method value, so laying the component out allocates nothing.

func (*MemoCache) Stats

func (c *MemoCache) Stats() (hits, misses uint64)

Stats returns how many layouts were served from cache (hits) and how many rebuilt the subtree (misses).

type NamedKey

type NamedKey struct {
	Name key.Name
	Mods key.Modifiers
}

NamedKey is a key with exactly the modifiers to hold, which an OnKey handler asks Gio for by name.

type OutOfFlow

type OutOfFlow interface {
	Element
	OutOfFlow()
}

OutOfFlow is implemented by elements that paint over the window and take no space where they're placed: Dialog, Sheet and Drawer. A box lays them out apart from its other children, so its Gap and Justify leave them out.

type Placement

type Placement int

Placement says on which side of its trigger a portal goes.

const (
	// PlaceAuto puts the portal below its trigger, or above it when
	// it wouldn't fit below.
	PlaceAuto Placement = iota
	// PlaceBelow and PlaceAbove keep it on one side.
	PlaceBelow
	PlaceAbove
)

type SemanticContainer

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

SemanticContainer is a container node being laid out: the nodes recorded until End become its children (their Parent is its ID).

func BeginSemanticGroup

func BeginSemanticGroup(n SemanticNode) *SemanticContainer

BeginSemanticGroup starts a container node - a list, a table, a dialog, a region - around laying out its content:

g := elements.BeginSemanticGroup(elements.SemanticNode{Kind: elements.SemanticList, Label: "Inbox", Target: l})
dims := content.Layout(gtx)
g.End(gtx, dims.Size)

Nodes recorded in between without a Parent get the group's ID.

func (*SemanticContainer) End

func (g *SemanticContainer) End(gtx layout.Context, size image.Point)

End records the group with its size at the current position and makes the nodes recorded since Begin its children.

func (*SemanticContainer) EndAt

func (g *SemanticContainer) EndAt(gtx layout.Context, r image.Rectangle)

EndAt is End for a container whose window rectangle is r, for a component placing its parts itself (a grid's rows).

func (*SemanticContainer) ID

func (g *SemanticContainer) ID() string

ID is the group's node ID, "" when no tree is recorded.

func (*SemanticContainer) SetLabel

func (g *SemanticContainer) SetLabel(label string)

SetLabel sets the group's label before End: a dialog titled by its content.

type SemanticKind

type SemanticKind string

SemanticKind classifies a node of the semantic tree.

const (
	SemanticText     SemanticKind = "text"
	SemanticButton   SemanticKind = "button"
	SemanticInput    SemanticKind = "input"
	SemanticCheckbox SemanticKind = "checkbox"
	SemanticSlider   SemanticKind = "slider"
	SemanticSelect   SemanticKind = "select"
	SemanticTab      SemanticKind = "tab"
	SemanticMenuItem SemanticKind = "menuitem"
	SemanticLink     SemanticKind = "link"
	SemanticImage    SemanticKind = "image"
	SemanticScroll   SemanticKind = "scroll"
	SemanticCustom   SemanticKind = "custom"

	SemanticHeading  SemanticKind = "heading"
	SemanticSwitch   SemanticKind = "switch"
	SemanticRadio    SemanticKind = "radio"
	SemanticProgress SemanticKind = "progress"
	SemanticGroup    SemanticKind = "group"
	SemanticList     SemanticKind = "list"
	SemanticListItem SemanticKind = "listitem"
	SemanticTable    SemanticKind = "table"
	SemanticRow      SemanticKind = "row"
	SemanticCell     SemanticKind = "cell"
	// SemanticColumnHeader is a table's column header cell.
	SemanticColumnHeader SemanticKind = "columnheader"
	SemanticDialog       SemanticKind = "dialog"
	// SemanticAlert is an urgent message: a dialog asking to confirm,
	// an error banner. Its text is announced when it appears.
	SemanticAlert    SemanticKind = "alert"
	SemanticStatus   SemanticKind = "status"
	SemanticMenu     SemanticKind = "menu"
	SemanticMenuBar  SemanticKind = "menubar"
	SemanticTabList  SemanticKind = "tablist"
	SemanticTabPanel SemanticKind = "tabpanel"
	SemanticTree     SemanticKind = "tree"
	SemanticTreeItem SemanticKind = "treeitem"
	SemanticComboBox SemanticKind = "combobox"
	SemanticToolbar  SemanticKind = "toolbar"
	// SemanticRegion is a landmark: a large part of the window a skip
	// link or a screen reader's landmark list goes to.
	SemanticRegion SemanticKind = "region"
)

type SemanticNode

type SemanticNode struct {
	// ID identifies the node. Nodes with a Target keep their ID for
	// the target's lifetime; others are numbered in layout order.
	ID string `json:"id"`
	// Kind classifies the node.
	Kind SemanticKind `json:"kind"`
	// Label is the visible text or accessible name.
	Label string `json:"label,omitempty"`
	// Value is the current value of a control (field text, checked
	// state, slider position).
	Value string `json:"value,omitempty"`
	// Bounds is the node's window-relative area, in pixels, including
	// for children of rows, stacks and scrolled content.
	Bounds image.Rectangle `json:"bounds"`
	// Disabled marks a control that doesn't accept input.
	Disabled bool `json:"disabled,omitempty"`
	// Scroll is the ID of the innermost scroll container the node is
	// laid out in, or "" outside any. A node in a scroll container may
	// lie outside the container's Bounds, scrolled out of view.
	Scroll string `json:"scroll,omitempty"`
	// Target is the stateful component behind the node, if any, so
	// automation can act on it (e.g. call Click). It is not
	// serialized.
	Target any `json:"-"`

	// Description is longer help read after the label (a hint, an error).
	Description string `json:"description,omitempty"`
	// Level is a heading's level, 1 to 6, or a tree item's depth from 1.
	Level int `json:"level,omitempty"`
	// Checked is a checkbox's, switch's or radio button's state.
	Checked CheckState `json:"checked,omitempty"`
	// Selected marks a selected tab, list item, row or option.
	Selected bool `json:"selected,omitempty"`
	// Expanded is an expandable control's state: a tree item, an
	// accordion section, a dropdown, a menu button.
	Expanded ExpandState `json:"expanded,omitempty"`
	// Required, Invalid and Busy mark a field that must be filled, one
	// whose value is wrong, and a part of the UI still loading.
	Required bool `json:"required,omitempty"`
	Invalid  bool `json:"invalid,omitempty"`
	Busy     bool `json:"busy,omitempty"`
	// Focused marks the node with keyboard focus.
	Focused bool `json:"focused,omitempty"`
	// Live makes changes to the node's label or value announced:
	// LivePolite after what's being read, LiveAssertive at once (an
	// error). Toasts, new chat messages and validation errors use it.
	Live LiveMode `json:"live,omitempty"`
	// Min, Max and Now are a slider's or progress bar's range and value.
	Min, Max, Now float64 `json:"-"`
	// Parent is the ID of the group, list, table, dialog or other
	// container the node is in, "" at the top.
	Parent string `json:"parent,omitempty"`
	// LabelledBy, DescribedBy and Controls relate the node to others by
	// ID: the nodes naming it, describing it, and those it controls (a
	// tab its panel, a combobox its list).
	LabelledBy  []string `json:"labelledBy,omitempty"`
	DescribedBy []string `json:"describedBy,omitempty"`
	Controls    []string `json:"controls,omitempty"`
	// Pos and Count are an item's place in its list or set, from 1, when
	// the list shows only some items (virtualized).
	Pos, Count int `json:"-"`
	// HasCaret marks a text field showing its caret: Caret is where it
	// is and Anchor the selection's other end, in runes from the start
	// of Value; Anchor == Caret is no selection.
	HasCaret      bool `json:"-"`
	Caret, Anchor int  `json:"-"`
}

SemanticNode describes one meaningful piece of the UI - a text run, a button, a field - as laid out in the last frame. The semantic tree is what automation (the built-in MCP server, tests) sees of the UI.

func EndSemantics

func EndSemantics() []SemanticNode

EndSemantics stops recording and returns the frame's nodes.

type StickyItem

type StickyItem struct {
	// Call paints it; Size is its size.
	Call op.CallOp
	Size image.Point
	// At is its position in the flow, absolute, kept exact as its
	// containers place it (TrackPosition).
	At image.Point
	// Top and Start stick it to those edges, Top and Left px in.
	Top, Start           bool
	TopOffset, StartOffs int
	// Track holds what it registered (portals, semantic nodes), moved
	// to where it's painted.
	Track ChildTracker
}

StickyItem is a sticky element waiting to be painted.

type StickyScope

type StickyScope struct {
	Items []*StickyItem
}

StickyScope collects the sticky elements of a scroll's content.

type TextInliner

type TextInliner interface {
	InlineText() string
}

TextInliner reports the text content of a text element, for diagnostics that name a container by the first text inside it.

type VisibleClip

type VisibleClip struct {
	// Origin is the container's window position, kept exact
	// (TrackPosition); Size its viewport.
	Origin image.Point
	Size   image.Point
	// Parent is the enclosing clip, nil at the window.
	Parent *VisibleClip
}

VisibleClip is the part of the window a scrolling container shows: content it lays out is visible only inside it, and inside each enclosing one. Drop targets use it so a target scrolled partly out of view only takes drops where it shows.

func CurrentVisibleClip

func CurrentVisibleClip() *VisibleClip

CurrentVisibleClip is the innermost visible clip, nil outside any scrolling container.

func (*VisibleClip) Rect

func (c *VisibleClip) Rect() image.Rectangle

Rect is the visible area: the clip's rectangle within its parents'.

type Watch

type Watch[T comparable] struct {
	Snap func() T
	// contains filtered or unexported fields
}

Watch is a Watcher over a snapshot of a component's fields: Snap returns the fields it draws from, as a comparable struct, which is compared with the one recorded when it last drew - without allocating, unlike a list of values. Set Snap once, when the component is made or first laid out.

func (*Watch[T]) Changed

func (w *Watch[T]) Changed() bool

Changed reports whether Snap differs from the recorded snapshot.

func (*Watch[T]) Commit

func (w *Watch[T]) Commit()

Commit records the snapshot the last Changed took: the fields as they were when the component started drawing.

type Watcher

type Watcher interface {
	Changed() bool
	Commit()
}

Watcher reports whether a component's own fields changed since it last drew them (Changed), and records the fields Changed saw once it has drawn them (Commit). Watch implements it.

Jump to

Keyboard shortcuts

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