el

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: AGPL-3.0 Imports: 40 Imported by: 0

README

ui/el

GPUI 风格的元素与视图:视图是普通 struct,每帧 Render 返回一棵链式样式搭起来的元素树;flexbox 布局;元素状态(悬停、滚动、输入框内容)按元素路径或 ID 自动保存;Agent 语义自动生成。

  • 依赖:core、theme、locale,以及内部的 ui/internal/loop、ui/internal/editorstyle、ui/internal/inputcontent。不依赖 kit、window。
  • 被谁依赖:应用代码。window 通过 FillsWindow 接口认出 el.Root,不引用本包。
文件 内容
element.go Element、Node、Styled[T] 的全部链式方法,Div、Text、Widget、Map;Decorate 包裹绘制,VisitWidgets 读取布局后的部件坐标
time.go 帧时间、声明式定时器、显式 key 与减少动画
overlay.go 声明式浮层、锚定定位、模态输入隔离、焦点约束与悬停查询
mount.go cx.Mount:把视图挂到窗口根部(kit 的 Dialog.Show、Sheet.Show、WindowNotifier 用它)
key_context.go KeyContext、cx.ActionAt、cx.Perform(菜单和命令面板按动作名执行)
scrollbar.go、scrollbar_mode.go 滚动条绘制、显示策略(含跟随系统)与淡入淡出
focus.go 原生焦点顺序、程序焦点、按键冒泡与默认激活、FocusVisible
input.go Input、TextArea
style.go Style、长度(Dp、Frac、Full)、对齐常量
layout.go、flow.go flexbox、换行与简单网格布局
paint.go 绘制、点击区域、滚动、输入框、语义信息
viewport.go 绘制坐标、可视区域与最近滚动容器的程序滚动
state.go 元素状态存储与回收;触屏长按打开右键菜单
root.go View、ViewFunc、Context、Root、Embed,每帧的执行顺序

使用指南:元素与视图。

input_paste.go 在默认文本插入前处理 OnPaste;可接入 core.ClipboardReader,原生读取失败回退 Gio 纯文本通路。异步完成通过 core.Update,编辑内容或选区变化后丢弃旧结果。

原子输入引用由 el.InputDocument 接入 ui/internal/inputcontent,后者只保存文本、引用范围、选区和编辑事务,不依赖 Gio 或其他 Keel 模块。kit 和 markdown 仅经 el 间接依赖它。

Documentation

Index

Constants

View Source
const ScrollbarLinger = 900 * time.Millisecond

ScrollbarLinger is the idle delay before Scrolling mode hides the bars.

Variables

View Source
var Auto = Length{}

Auto sizes an element to its content, or stretches it where the parent aligns items with Stretch.

View Source
var Full = Frac(1)

Full is Frac(1).

Functions

func ContainerContentSize

func ContainerContentSize(container Element) image.Point

ContainerContentSize reports a container's laid-out content size in pixels, before its own Min/Max dimensions or Reveal are applied. Call after layout, for example from Decorate. Text, input and widget leaves return zero.

func ElementBounds

func ElementBounds(root, target Element) (image.Rectangle, bool)

ElementBounds returns target's border box relative to root after layout, before scrolling translations. Hidden and unrelated elements return false. Call from Decorate, using elements from the current tree.

func ReducedMotion

func ReducedMotion() bool

ReducedMotion returns the application override; platforms without a native preference bridge default to false. Set through theme.SetReducedMotion.

func SetScrollbarDefault added in v0.0.5

func SetScrollbarDefault(mode ScrollbarMode)

SetScrollbarDefault sets the mode of scroll containers that do not choose one, ScrollbarAlways by default. Pass ScrollbarSystem to follow the platform. Windows redraw on their next frame.

func VisitWidgets

func VisitWidgets(root Element, metric unit.Metric, visit func(core.Widget, image.Rectangle))

VisitWidgets visits widgets in tree order with their content bounds relative to root, after layout. It includes widgets outside the viewport, skips hidden elements, and reports layout coordinates before any ScrollY translations.

func WriteClipboard

func WriteClipboard(text string)

WriteClipboard copies text to the system clipboard. Call it from a handler, e.g. a copy button's OnClick; it takes effect in the current frame.

Types

type Align

type Align uint8

Align positions children along an axis.

const (
	Start Align = iota
	Center
	End
	Stretch       // cross axis only: fill the container
	SpaceBetween  // main axis only
	SpaceAround   // main axis only
	ContentBottom // row cross axis only: align selected descendant bottoms
)

type Context

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

Context is passed to Render.

func (*Context) Action

func (cx *Context) Action(name string, fn func())

Action handles a named action from the keymap (core.Bind) while the window has focus and this view is rendered: every chord bound to name runs fn. Rebinding takes effect on the next frame; an unbound action does nothing.

func (*Context) ActionAt

func (cx *Context) ActionAt(targetID, action string, fn func())

ActionAt handles an action while focus is within targetID, resolving chords through its current KeyContext ancestry and then core.Bind. Declare it every frame. Do not also register the same action through the global Action method. The innermost focused target wins for repeated actions or chords; ties use declaration order. An inner empty binding also suppresses outer handlers. Perform runs the handler as if from targetID (see Perform).

func (*Context) After

func (cx *Context) After(key any, d time.Duration, fn func())

After declares a one-shot timer with a comparable key unique to this root. Declare the key on every Render while the timer is alive; omitting it cancels it. Changing d restarts the timer. A fired timer does not rearm until omitted for a frame. Do not declare timers in Cache builders, which may not run again.

func (*Context) AfterEnabled

func (cx *Context) AfterEnabled(id string, key any, d time.Duration, fn func())

AfterEnabled is After scoped to a visible, enabled element ID. Its full delay restarts after that element or an ancestor is disabled, hidden, or covered by a modal layer. Declare it every Render, like After.

func (*Context) Animating

func (cx *Context) Animating()

Animating requests the next animation frame without spawning a goroutine.

func (*Context) Cache

func (cx *Context) Cache(key any, build func() Element) Element

Cache returns the element built for key, calling build only when key was not used in the previous frame. While the width it is given stays the same, the element's layout is reused too, so long, mostly unchanging content (a chat history, a rendered document) costs little per frame. key must be comparable and change whenever the element would look different; the element must not depend on anything else. Entries unused for a frame are dropped. Applying a theme also rebuilds cached elements.

func (*Context) ClickModifiers

func (cx *Context) ClickModifiers() key.Modifiers

ClickModifiers reports modifier keys during the current pointer click callback (including double click); outside that callback it returns zero.

func (*Context) Countdown

func (cx *Context) Countdown(id string, key any, d time.Duration, paused bool, fn func())

Countdown is a one-shot timer scoped to a visible, enabled owner. Pausing, hiding, disabling or covering the owner preserves the remaining delay. Changing d restarts it; omitting the declaration cancels it, like After.

func (*Context) Enabled

func (cx *Context) Enabled(id string) bool

Enabled reports whether the last declared element with id accepts input, including ancestor disabled state and modal blocking. Missing IDs are false. During Render this describes the previous declaration, like FocusWithin.

func (*Context) Focus

func (cx *Context) Focus(id string)

Focus requests focus by ID in this root. It is applied after painting. The first visible Focusable element or input with that ID wins. An empty ID clears focus; missing, hidden or off-screen targets leave the current focus alone. Call from Render or its callbacks; IDs should be unique within a root.

func (*Context) FocusVisible added in v0.0.4

func (cx *Context) FocusVisible(id string) bool

FocusVisible reports whether the element with id has focus that should show a ring: focus from the keyboard or a program, not from a pointer press. Controls that draw their ring on a part use it with a transparent FocusStyle on the focusable element.

func (*Context) FocusWithin

func (cx *Context) FocusWithin(id string) bool

FocusWithin reports whether the element with id, or anything inside it, had focus in the last painted frame. Tooltips use it for keyboard focus.

func (*Context) Focused

func (cx *Context) Focused(id string) bool

func (*Context) Hovered

func (cx *Context) Hovered(id string) bool

Hovered reports the last processed pointer position for a visible ID. Disabled elements and elements behind a modal layer are never hovered.

func (*Context) InputAction

func (cx *Context) InputAction(id string, action InputAction)

InputAction queues a command for the next paint of an enabled input. Read-only inputs reject Cut/Paste; password inputs reject Copy/Cut. Paste uses the system clipboard's asynchronous text path and the input's normal filter/transform.

func (*Context) InputSelection

func (cx *Context) InputSelection(id string) (InputEdit, bool)

InputSelection returns the input's last editor text and rune selection. Missing or disabled inputs return false. It does not change focus.

func (*Context) LastSize

func (cx *Context) LastSize(id string) (width, height float32)

LastSize returns the last painted border-box size of an identified element, in dp. Read during Render; zero means the element has not been painted or was clipped out. Unlike scroll state, geometry also updates on disabled frames.

func (*Context) LayoutSize

func (cx *Context) LayoutSize(element Element) (width, height float32)

LayoutSize returns an element's final border-box size in dp. Read it only during Decorate, after layout has finished; it also works for clipped rows.

func (*Context) Mount added in v0.0.5

func (cx *Context) Mount(key any, view View)

Mount renders view with this root every frame until Unmount(key). Mounting a key again replaces its view in place. Call it from Render or a callback; the view shows from the next render.

func (*Context) Mounted added in v0.0.5

func (cx *Context) Mounted(key any) bool

Mounted reports whether a view is mounted at key.

func (*Context) MountedView added in v0.0.5

func (cx *Context) MountedView(key any) View

MountedView returns the view mounted at key, or nil.

func (*Context) Now

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

Now is the frame timestamp. Animations must derive their phase from it.

func (*Context) Overlay

func (cx *Context) Overlay(key any, layer *Layer)

Overlay declares a layer in paint order. key must be comparable and unique within this root. Omission closes the layer; OnDismiss asks the owner to omit it. Declare outside Cache builders. Root supports full-window layers; Embed uses its maximum constraints and deferred painting as a best-effort fallback.

func (*Context) PaintGeometry

func (cx *Context) PaintGeometry() (origin image.Point, viewport image.Rectangle)

PaintGeometry reports the current element's origin and clipped viewport in root coordinates. Use it only from Decorate, while the element is painted. It lets input handlers keep a pointer stationary as ancestors scroll.

func (*Context) Perform added in v0.0.5

func (cx *Context) Perform(targetID, action string) bool

Perform runs the handler a key press bound to action would run with focus at targetID: the innermost ActionAt declared on targetID or an element enclosing it, else a global Action handler. It works without any key bound, which is what menus and command palettes need. Call it from a callback; it sees this frame's declarations and reports whether a handler ran. Hidden or disabled targets run nothing.

func (*Context) PixelScale

func (cx *Context) PixelScale() float32

PixelScale returns the current number of physical pixels per dp. It is available during Render and defaults to one for an unset metric.

func (*Context) ScrollBy

func (cx *Context) ScrollBy(dy int) int

ScrollBy schedules a pixel delta on the nearest enclosing ScrollY container and returns the amount it can scroll. Call during Decorate. The next frame applies it before drawing children, so their input and painting agree.

func (*Context) ScrollIntoView

func (cx *Context) ScrollIntoView(id string, top, bottom float32)

ScrollIntoView scrolls the ScrollY element with id as little as needed to show [top, bottom], in dp of its content. It applies when the element is next painted, so call it from Render or a callback.

func (*Context) ScrollIntoViewX

func (cx *Context) ScrollIntoViewX(id string, left, right float32)

ScrollIntoViewX minimally reveals [left, right] in a ScrollX content box.

func (*Context) ScrollState

func (cx *Context) ScrollState(id string) (offset, viewport, content float32)

ScrollState reports, in dp, the scroll offset, viewport height and content height of the ScrollY element with id as last painted; all zero before its first frame. Virtual lists use it to build only the rows that show.

func (*Context) ScrollStateX

func (cx *Context) ScrollStateX(id string) (offset, viewport, content float32)

ScrollStateX is ScrollState for the horizontal axis; values are in dp.

func (*Context) ScrollTo

func (cx *Context) ScrollTo(id string, offset float32)

ScrollTo sets a ScrollY offset in dp on its next paint. The new content size clamps it then, so callers can preserve an anchor as content changes. It does nothing before the container's first paint or in read-only layout.

func (*Context) ScrollToX

func (cx *Context) ScrollToX(id string, offset float32)

ScrollToX sets a ScrollX offset in dp on its next paint. Content bounds clamp it during painting. Missing containers and read-only layout are ignored.

func (*Context) SelectInput

func (cx *Context) SelectInput(id string, start, end int)

SelectInput schedules rune-based selection in an input after its next Bind synchronization. It does not change text or focus. Missing or disabled inputs are ignored, and the editor clamps the endpoints to its content.

func (*Context) Shortcut

func (cx *Context) Shortcut(chord string, fn func())

Shortcut binds a key chord such as "mod+s" to fn while the window has focus and this view is rendered. It panics on an invalid chord.

func (*Context) Themed

func (cx *Context) Themed(p theme.Palette, v View) *DivEl

Themed renders a view with another palette, for a part of the window in different colors: a dark sidebar in a light window, a preview of a theme. The palette applies while the view renders and while it paints, so kit components and custom drawing inside follow it; the rest of the window keeps the global theme. The wrapper stretches its child; set its background to fill the area.

func (*Context) Unmount added in v0.0.5

func (cx *Context) Unmount(key any)

Unmount stops rendering the view mounted at key.

func (*Context) ViewportSize

func (cx *Context) ViewportSize() (width, height float32)

ViewportSize returns this root's available width and height in dp. It is available during Render, before child layout, for sizing window-bound overlays.

type DivEl

type DivEl struct{ Styled[DivEl] }

DivEl is a box: the only element with children.

func Div

func Div() *DivEl

Div creates an empty box. Children stack top to bottom unless Row is set.

func KeyHint

func KeyHint(action, targetID string, build func(chord string) Element) *DivEl

KeyHint builds a hint for the first chord resolved at targetID. Resolution happens after the current element tree is built, before measuring it, so initial-frame hints see the target's current KeyContext ancestry. Missing, hidden or disabled targets and unbound actions render no content. The builder must return display-only content, without declaring overlays or shortcuts.

type DragEvent

type DragEvent struct {
	Kind       DragKind
	Canceled   bool // DragEnd caused by cancellation rather than release
	X, Y, W, H float32
}

DragEvent reports a pointer drag in dp, relative to the element's top left corner; W and H are the element's size, so X/W is a fraction of its width. X and Y may fall outside 0..W and 0..H while the pointer is outside.

type DragKind

type DragKind uint8

DragKind is the phase of a drag.

const (
	DragStart DragKind = iota // the pointer went down on the element
	DragMove                  // it moved while down, even outside the element
	DragEnd                   // it went up, or the drag was cancelled
)

type Edges

type Edges struct{ Top, Right, Bottom, Left float32 }

Edges are per-side lengths in dp.

type Element

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

Element is a node of the tree a View renders each frame. Build elements with Div, Text, Input and Widget; they are cheap, and a new tree is built on every frame.

func Map

func Map[T any](items []T, fn func(int, T) Element) []Element

Map builds one element per item, for Children.

type InputAction

type InputAction uint8

InputAction is an editing command directed to one identified input.

const (
	InputCopy InputAction = iota
	InputCut
	InputPaste
	InputSelectAll
)

type InputContent

type InputContent = inputcontent.Content

func NewInputContent

func NewInputContent(text string, tokens ...InputTokenSpan) (InputContent, error)

NewInputContent validates UTF-8 byte ranges and returns an immutable draft.

type InputDocument

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

InputDocument retains reference metadata, selection and undo history for one input. Do not attach the same document to multiple live editors.

func (*InputDocument) Content

func (d *InputDocument) Content() InputContent

func (*InputDocument) ReplaceWithToken

func (d *InputDocument) ReplaceWithToken(token InputToken) error

func (*InputDocument) Select

func (d *InputDocument) Select(r InputRange) error

func (*InputDocument) SelectedToken

func (d *InputDocument) SelectedToken() (InputToken, bool)

SelectedToken returns a completely selected reference.

func (*InputDocument) Selection

func (d *InputDocument) Selection() InputRange

func (*InputDocument) SetContent

func (d *InputDocument) SetContent(c InputContent)

func (*InputDocument) SetText

func (d *InputDocument) SetText(text string) error

type InputEdit

type InputEdit struct {
	Text       string
	Start, End int
}

InputEdit describes text and rune-based selection endpoints after an edit.

type InputEl

type InputEl struct{ Styled[InputEl] }

InputEl is a text box. Its editing state (content, caret, selection) is kept per element, so give it an ID when siblings may change.

func Input

func Input() *InputEl

Input creates a single-line text box. Enter triggers OnSubmit.

func TextArea

func TextArea() *InputEl

TextArea creates a multi-line text box; Enter inserts a newline.

func (*InputEl) AutoGrow

func (e *InputEl) AutoGrow(minRows, maxRows int) *InputEl

AutoGrow sizes a multiline input to its wrapped text, between minRows and maxRows lines. Overflow scrolls inside the editor. Invalid ranges are ignored. Passing (0, 0) restores the default height. Single-line inputs ignore this.

func (*InputEl) Bind

func (e *InputEl) Bind(p *string) *InputEl

Bind keeps *p and the box in sync: typing writes *p, and a program change to *p shows in the box on the next frame.

func (*InputEl) CaptureKeys

func (e *InputEl) CaptureKeys(names ...string) *InputEl

CaptureKeys reserves named, unmodified keys for OnKey before the single-line editor handles them. The handler owns these keys even when it returns false. Ordinary editing shortcuts with modifiers remain with the editor.

func (*InputEl) Document

func (e *InputEl) Document(d *InputDocument) *InputEl

Document binds an atomic-reference draft. It owns text and undo; Bind, Transform, password masks, Filter and MaxLen are not applied in this mode.

func (*InputEl) Filter

func (e *InputEl) Filter(chars string) *InputEl

Filter accepts only the runes in chars as typed or pasted input; "" accepts all.

func (*InputEl) MaxLen

func (e *InputEl) MaxLen(n int) *InputEl

MaxLen limits the content to n runes; 0 means no limit.

func (*InputEl) OnChange

func (e *InputEl) OnChange(fn func(string)) *InputEl

OnChange runs after every edit by the user, with the new content.

func (*InputEl) OnPaste

func (v *InputEl) OnPaste(fn func(core.ClipboardData) bool) *InputEl

OnPaste handles clipboard contents before default text insertion. Return true to consume them. It applies to keyboard and InputPaste commands; nil restores ordinary text paste. Read-only and disabled inputs do not invoke the handler.

func (*InputEl) OnPasteError

func (v *InputEl) OnPasteError(fn func(error)) *InputEl

OnPasteError reports read failures before fallback or rejection of oversized text. It runs on the UI thread; nil suppresses error reporting.

func (*InputEl) OnSubmit

func (e *InputEl) OnSubmit(fn func(string)) *InputEl

OnSubmit runs when Enter is pressed in a single-line box.

func (*InputEl) OnTokenActivate

func (e *InputEl) OnTokenActivate(fn func(InputToken)) *InputEl

OnTokenActivate runs for an unmodified token click, including in read-only fields. Dragging a selection and disabled fields do not activate references.

func (*InputEl) Password

func (e *InputEl) Password() *InputEl

Password masks the content.

func (*InputEl) PasteReader

func (v *InputEl) PasteReader(reader core.ClipboardReader) *InputEl

PasteReader supplies rich clipboard contents. Without one, OnPaste receives Gio's text contents. Failed reads fall back to the Gio text path.

func (*InputEl) Placeholder

func (e *InputEl) Placeholder(s string) *InputEl

Placeholder is shown while the box is empty; agents also see it as the name when Name is not set.

func (*InputEl) ReadOnly

func (e *InputEl) ReadOnly(on bool) *InputEl

ReadOnly lets the user select and copy but not edit.

func (*InputEl) SelectOnFocus

func (e *InputEl) SelectOnFocus(on bool) *InputEl

SelectOnFocus selects the complete value when the input gains focus.

func (*InputEl) TokenRenderer

func (e *InputEl) TokenRenderer(fn InputTokenRenderer) *InputEl

func (*InputEl) Transform

func (e *InputEl) Transform(fn func(InputEdit) InputEdit) *InputEl

Transform normalizes user edits before Bind and OnChange. Return mapped rune selection endpoints with the new text. Programmatic Bind changes are unchanged. Transformed inputs retain up to 100 user edits for undo/redo; programmatic changes reset this history.

func (*InputEl) TransformEdit

func (e *InputEl) TransformEdit(fn func(before, after InputEdit) InputEdit) *InputEl

TransformEdit normalizes an edit with access to the previous text and rune selection. It replaces Transform; undo/redo restores normalized snapshots.

type InputRange

type InputRange = inputcontent.Range

type InputToken

type InputToken = inputcontent.Token

InputToken identifies an atomic reference. Text is the submitted/copied value; Label, when nonempty, is its visible name.

type InputTokenRenderer

type InputTokenRenderer func(core.C, InputToken) core.D

InputTokenRenderer lays out passive reference content in physical pixels. It is measured with a disabled context, then painted at the resulting inline position. Honor Constraints and return a baseline (distance from the bottom). Do not mutate application state or install input handlers; use OnTokenActivate. Nil restores the default label pill. Content is clipped to the input viewport.

type InputTokenSpan

type InputTokenSpan = inputcontent.Span

type KeyEvent

type KeyEvent struct {
	Name      string
	Modifiers key.Modifiers
	State     KeyState
}

KeyEvent keeps the el API independent of the Gio event structure.

type KeyState

type KeyState uint8

KeyState distinguishes key presses from releases.

const (
	KeyPress KeyState = iota
	KeyRelease
)

type Layer

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

Layer describes an overlay for one Render. Declare it again while open.

func Anchored

func Anchored(anchorID string, content Element) *Layer
func Modal(content Element) *Layer

func (*Layer) Arrow

func (l *Layer) Arrow(on bool) *Layer

Arrow adds a 6dp pointer to an anchored layer. Offset measures to its tip. It follows the actual placement, including flips, and uses the panel background.

func (*Layer) BeforeDismiss

func (l *Layer) BeforeDismiss(fn func() bool) *Layer

BeforeDismiss may reject Esc/outside dismissal. Owner removal bypasses it.

func (*Layer) KeepOnEscape

func (l *Layer) KeepOnEscape() *Layer

KeepOnEscape consumes Esc without dismissing this layer or layers below it.

func (*Layer) KeepOnOutsidePress

func (l *Layer) KeepOnOutsidePress() *Layer

KeepOnOutsidePress stops presses outside the layer from calling OnDismiss; Esc still does. A destructive confirmation uses it so a stray click on the scrim cannot cancel it. A modal layer still blocks the press.

func (*Layer) MatchAnchorWidth

func (l *Layer) MatchAnchorWidth() *Layer

MatchAnchorWidth sizes the layer to its anchor's width, as a dropdown matches its trigger.

func (*Layer) Modal

func (l *Layer) Modal() *Layer

func (*Layer) Offset

func (l *Layer) Offset(dp float32) *Layer

func (*Layer) OnDismiss

func (l *Layer) OnDismiss(fn func()) *Layer

func (*Layer) OnEscape

func (l *Layer) OnEscape(fn func() bool) *Layer

OnEscape handles an Escape press before normal dismissal. Returning true consumes the press and keeps the layer open; false permits normal dismissal. KeepOnEscape takes precedence. Outside presses do not call this callback.

func (*Layer) Owner

func (l *Layer) Owner(id string) *Layer

Owner ties a layer's lifetime to an enabled element in the current tree. Use this for modals declared by a component nested in a disabled or hidden container. The owner controls eligibility, not position or modality.

func (*Layer) Placement

func (l *Layer) Placement(side Side, align Align) *Layer

Placement places an Anchored layer at side of its anchor. On a Modal it places the content against that edge of the root instead of centering it, e.g. a sheet: Modal(panel).Placement(Right, Start).

func (*Layer) Scrim

func (l *Layer) Scrim(on bool) *Layer

func (*Layer) TopInset

func (l *Layer) TopInset(dp float32) *Layer

TopInset reserves space above an edge-positioned modal, in dp. The inset is capped at the root height. Other layer placements ignore it. The scrim still covers the root; painting and input stay below the inset, even in animation.

func (*Layer) TrapFocus

func (l *Layer) TrapFocus() *Layer

type Length

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

Length is a size along one axis: automatic, a fixed number of dp or sp, or a fraction of the parent's content box.

func Dp

func Dp(v float32) Length

Dp is a fixed length.

func Frac

func Frac(f float32) Length

Frac is a fraction of the parent's content box: Frac(1) is the full width.

func Sp

func Sp(v float32) Length

Sp is a fixed length that follows the user's font scale.

type Node

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

Node holds what an element was built with and, after layout, where it is.

type RootWidget

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

RootWidget renders a View as a core.Widget.

func Embed

func Embed(v View) *RootWidget

Embed renders v as an ordinary widget sized to its content, e.g. inside hand-written Gio layout or a window that pads and scrolls its content.

func Root

func Root(v View) *RootWidget

Root makes v the whole content of a window: it fills the window, with the theme background, and the window adds no padding or scrolling of its own.

window.Open(window.Options{Title: "Orders", Content: el.Root(&Orders{})})

func (*RootWidget) FillsWindow

func (r *RootWidget) FillsWindow() bool

FillsWindow tells ui/window to give the root the whole window.

func (*RootWidget) Layout

func (r *RootWidget) Layout(gtx core.C) core.D

type ScrollEvent

type ScrollEvent struct{ X, Y float32 }

ScrollEvent reports scroll deltas in dp. Gio does not identify discrete wheels versus trackpads or expose a gesture-end phase on this event.

type ScrollRange

type ScrollRange struct{ Min, Max float32 }

ScrollRange is the signed range of scroll deltas accepted in dp. A zero range passes that axis to enclosing scroll handlers.

type ScrollbarMode

type ScrollbarMode uint8

ScrollbarMode controls when an overflowing scroll container shows its bars. It applies to both axes and does not change the content's layout or offset.

const (
	ScrollbarAlways    ScrollbarMode = iota // visible whenever content overflows
	ScrollbarHover                          // visible while the pointer is inside the viewport or dragging a bar
	ScrollbarScrolling                      // visible during offset changes and briefly afterward
	// ScrollbarSystem follows the platform's setting: macOS "Show scroll
	// bars", Windows "Automatically hide scroll bars". Elsewhere it is Always.
	ScrollbarSystem
)

func SystemScrollbars added in v0.0.5

func SystemScrollbars() ScrollbarMode

SystemScrollbars is the platform's preference as last read: Scrolling where bars hide at rest, otherwise Always. ui/window reads the setting into theme.SystemScrollbarsAutoHide.

type Side

type Side uint8

Side selects the edge of an anchor at which a layer is placed.

const (
	Bottom Side = iota
	Top
	Left
	Right
)

type Style

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

Style is everything an element can look like. Build it with the methods shared by all elements (see Styled); Hover and Active take a func that changes a Style, whose methods mirror the element ones.

func (*Style) Bg

func (s *Style) Bg(c color.NRGBA) *Style

Visual changes, usable in Hover and Active. They return the Style so calls chain.

func (*Style) BgGradient

func (s *Style) BgGradient(g theme.Gradient) *Style

BgGradient fills the background with a linear gradient instead of a solid color; a later Bg replaces it. A zero gradient changes nothing, so a theme's optional gradient can be passed as is.

func (*Style) BorderColor

func (s *Style) BorderColor(c color.NRGBA) *Style

func (*Style) BorderDashed

func (s *Style) BorderDashed(on bool) *Style

BorderDashed switches the border between dashed and solid.

func (*Style) TextColor

func (s *Style) TextColor(c color.NRGBA) *Style

type Styled

type Styled[T any] struct {
	// contains filtered or unexported fields
}

Styled carries the builder methods every element shares. T is the element type, so each method returns it and calls chain: Div().P(8).Bg(c).Child(...).

func (*Styled[T]) Absolute

func (s *Styled[T]) Absolute() *T

Absolute takes the element out of flow and places it by Top/Right/Bottom/Left within its parent's padding box.

func (*Styled[T]) Active

func (s *Styled[T]) Active(fn func(*Style)) *T

func (*Styled[T]) AspectRatio

func (s *Styled[T]) AspectRatio(ratio float32) *T

AspectRatio derives an automatic height from a resolved width (width/height). Explicit heights take precedence. Zero clears the ratio; invalid values are ignored.

func (*Styled[T]) Bg

func (s *Styled[T]) Bg(c color.NRGBA) *T

func (*Styled[T]) BgGradient

func (s *Styled[T]) BgGradient(g theme.Gradient) *T

BgGradient fills the background with a linear gradient; see Style.BgGradient.

func (*Styled[T]) Bold

func (s *Styled[T]) Bold() *T

func (*Styled[T]) Border

func (s *Styled[T]) Border(dp float32, c color.NRGBA) *T

Border draws a line of width dp inside the element's edge.

func (*Styled[T]) BorderDashed

func (s *Styled[T]) BorderDashed(on bool) *T

BorderDashed draws 4dp dashes with 3dp gaps; false restores a solid border.

func (*Styled[T]) Bottom

func (s *Styled[T]) Bottom(dp float32) *T

func (*Styled[T]) Center

func (s *Styled[T]) Center() *T

Center centers children on both axes.

func (*Styled[T]) Child

func (s *Styled[T]) Child(children ...Element) *T

Child appends children; nil elements are skipped.

func (*Styled[T]) Children

func (s *Styled[T]) Children(children []Element) *T

Children is Child for a slice, e.g. from Map.

func (*Styled[T]) Col

func (s *Styled[T]) Col() *T

Col lays children out top to bottom (the default).

func (*Styled[T]) ColSpan

func (s *Styled[T]) ColSpan(columns int) *T

ColSpan sets how many tracks a child occupies in a Grid. Values are clamped to 1..the parent's column count; a cell that does not fit starts a new row.

func (*Styled[T]) ContentBottom

func (s *Styled[T]) ContentBottom(target Element) *T

ContentBottom selects an in-flow descendant whose border-box bottom aligns with siblings in a row using Items(ContentBottom). Nil, hidden, or missing descendants fall back to this element's bottom. This is geometric alignment, not a font baseline. Pass an element from the current render tree.

func (*Styled[T]) Cursor

func (s *Styled[T]) Cursor(c pointer.Cursor) *T

Cursor sets the pointer shape over the element, e.g. pointer.CursorColResize on a splitter.

func (*Styled[T]) CursorPointer

func (s *Styled[T]) CursorPointer() *T

CursorPointer shows a hand over the element.

func (*Styled[T]) Decorate

func (s *Styled[T]) Decorate(fn func(gtx core.C, draw func())) *T

Decorate wraps painting with custom operations, e.g. a shared input area around a subtree. gtx uses the element's coordinate system and exact size. Call draw once to paint the element and its children. This does not run during measurement, and must not change the element tree or its layout.

func (*Styled[T]) Disabled

func (s *Styled[T]) Disabled(v bool) *T

func (*Styled[T]) DisabledStyle

func (s *Styled[T]) DisabledStyle(fn func(*Style)) *T

func (*Styled[T]) DragAccept

func (s *Styled[T]) DragAccept(fn func(dx, dy float32) bool) *T

DragAccept decides once, after the initial movement exceeds 3dp, whether this element captures a drag. dx/dy are pointer displacement in dp (not scroll deltas). Rejection emits a canceled DragEnd and leaves enclosing handlers free to capture. Nil restores ordinary OnDrag behavior. Presses on interactive descendants are left to those descendants. The predicate must not mutate UI state. Use with OnDrag.

func (*Styled[T]) Flex

func (s *Styled[T]) Flex(w float32) *T

Flex grows like Grow, taking free space in proportion to w: a child with Flex(2) gets twice the share of one with Flex(1) or Grow.

func (*Styled[T]) FocusOnPress

func (s *Styled[T]) FocusOnPress(id string) *T

FocusOnPress makes a press anywhere in this box that no child takes focus the element with id, such as the input inside a field's frame: clicking the frame's padding or beside the text then focuses the text. The box shows the text cursor; it gets no role and no Tab stop. It needs an ID of its own. An Input already does this for its own padding.

func (*Styled[T]) FocusStyle

func (s *Styled[T]) FocusStyle(fn func(*Style)) *T

FocusStyle sets a visual keyboard/programmatic focus style, like Hover. Pointer focus on non-input elements does not show it. Inputs always show it. It does not change layout. The default focus style is a 2dp Primary border inside the element bounds.

func (*Styled[T]) FocusTrap

func (s *Styled[T]) FocusTrap(on bool) *T

FocusTrap cycles Tab and Shift+Tab within this subtree while it contains focus. Nested traps use the innermost focused scope. Pointer and explicit Context.Focus requests can move to another scope; this does not open a modal, focus on mount, or restore focus on removal. Use Layer.TrapFocus for overlays. Targets belong to this el root; independently embedded widgets own their focus.

func (*Styled[T]) Focusable

func (s *Styled[T]) Focusable(on bool) *T

Focusable adds the element to the native Tab order and focuses it on press. Input and TextArea already manage their native editor focus.

func (*Styled[T]) Gap

func (s *Styled[T]) Gap(dp float32) *T

Gap puts dp between children.

func (*Styled[T]) Grid

func (s *Styled[T]) Grid(columns int) *T

Grid lays children in equal-width columns (at least one), in row order. Columns honor fixed/minimum child widths; rows size to their tallest child. Gap applies between columns and rows. Children can span tracks with ColSpan.

func (*Styled[T]) Grow

func (s *Styled[T]) Grow() *T

Grow lets the element take free space along its parent's main axis.

func (*Styled[T]) H

func (s *Styled[T]) H(l Length) *T

func (*Styled[T]) HFull

func (s *Styled[T]) HFull() *T

func (*Styled[T]) Hidden

func (s *Styled[T]) Hidden(h bool) *T

Hidden removes the element from layout and paint.

func (*Styled[T]) Hover

func (s *Styled[T]) Hover(fn func(*Style)) *T

State variants: visual changes while hovered or pressed.

func (*Styled[T]) ID

func (s *Styled[T]) ID(id string) *T

ID names the element among its siblings. State that outlives a frame, such as hover, scroll position and text box content, is kept per ID; give items of lists that change an ID so their state follows them.

func (*Styled[T]) IsHidden

func (s *Styled[T]) IsHidden() bool

IsHidden reports the element's declared visibility, before ancestor inheritance. Composite views can use it to keep adjoining controls hidden with their body.

func (*Styled[T]) Items

func (s *Styled[T]) Items(a Align) *T

Items aligns children across the main axis: Start, Center, End or Stretch (default for columns: children fill the width).

func (*Styled[T]) Justify

func (s *Styled[T]) Justify(a Align) *T

Justify places children along the main axis: Start, Center, End, SpaceBetween, SpaceAround.

func (*Styled[T]) KeepBottomOn

func (s *Styled[T]) KeepBottomOn(version int) *T

KeepBottomOn keeps the distance from the bottom of a ScrollY element when version changes, so content inserted above (older chat history) does not move what is on screen. Bump version in the same callback that inserts.

func (*Styled[T]) KeyContext

func (s *Styled[T]) KeyContext(name string) *T

KeyContext names a keymap scope inherited by descendants. Nested scopes override outer ones per action; an empty name adds no scope. Pair it with core.BindIn and Context.ActionAt for focused command handling.

func (*Styled[T]) Left

func (s *Styled[T]) Left(dp float32) *T

func (*Styled[T]) LineHeight

func (s *Styled[T]) LineHeight(scale float32) *T

LineHeight sets the distance between lines as a multiple of the text size, e.g. 1.5 for long paragraphs; descendants inherit it.

func (*Styled[T]) M

func (s *Styled[T]) M(v float32) *T

func (*Styled[T]) MaxH

func (s *Styled[T]) MaxH(l Length) *T

func (*Styled[T]) MaxLines

func (s *Styled[T]) MaxLines(n int) *T

MaxLines truncates text to n lines with an ellipsis.

func (*Styled[T]) MaxW

func (s *Styled[T]) MaxW(l Length) *T

func (*Styled[T]) Mb

func (s *Styled[T]) Mb(v float32) *T

func (*Styled[T]) Medium

func (s *Styled[T]) Medium() *T

Medium sets a weight between regular and Bold, for emphasis that should not shout: selected tabs, table headers.

func (*Styled[T]) MinH

func (s *Styled[T]) MinH(l Length) *T

func (*Styled[T]) MinW

func (s *Styled[T]) MinW(l Length) *T

func (*Styled[T]) Ml

func (s *Styled[T]) Ml(v float32) *T

func (*Styled[T]) Mono

func (s *Styled[T]) Mono() *T

Mono sets theme.MonoFace: code and numbers that must line up.

func (*Styled[T]) Mr

func (s *Styled[T]) Mr(v float32) *T

func (*Styled[T]) Mt

func (s *Styled[T]) Mt(v float32) *T

func (*Styled[T]) Mx

func (s *Styled[T]) Mx(v float32) *T

func (*Styled[T]) My

func (s *Styled[T]) My(v float32) *T

func (*Styled[T]) Name

func (s *Styled[T]) Name(name string) *T

Name sets the name agents see; by default it is the text inside.

func (*Styled[T]) NoShrink

func (s *Styled[T]) NoShrink() *T

NoShrink keeps the element from shrinking below its content size.

func (*Styled[T]) OnClick

func (s *Styled[T]) OnClick(fn func()) *T

OnClick runs fn on a primary click. It runs before the next render, so the frame that follows already shows its effects.

func (*Styled[T]) OnContextMenu

func (s *Styled[T]) OnContextMenu(fn func()) *T

OnContextMenu runs fn on a secondary pointer press. It does not consume primary clicks; add an OnKey handler for a keyboard context-menu action.

func (*Styled[T]) OnDoubleClick

func (s *Styled[T]) OnDoubleClick(fn func()) *T

OnDoubleClick runs fn on a double click (OnClick also sees both clicks).

func (*Styled[T]) OnDrag

func (s *Styled[T]) OnDrag(fn func(DragEvent)) *T

OnDrag reports presses, moves and releases on the element, e.g. for a slider thumb or a splitter. A press also starts an OnClick if both are set.

func (*Styled[T]) OnKey

func (s *Styled[T]) OnKey(fn func(KeyEvent) bool) *T

OnKey handles keys from a focused Focusable element, bubbling through its ancestors. Return true to stop bubbling and suppress default activation. Tab remains platform focus navigation; use Context.Shortcut for global keys.

func (*Styled[T]) OnMousePress

func (s *Styled[T]) OnMousePress(button pointer.Buttons, fn func()) *T

OnMousePress observes a primary, secondary or tertiary press without consuming descendant events or adding a Tab stop. Chords are ignored. It shares a handler with OnContextMenu; the last call wins. Zero clears it; invalid buttons are ignored.

func (*Styled[T]) OnScroll

func (s *Styled[T]) OnScroll(x, y ScrollRange, fn func(ScrollEvent)) *T

OnScroll receives scroll input within the supplied axis ranges. Excess is routed by Gio to enclosing handlers. Descendant handlers have priority. Nil removes the handler; disabled/hidden ancestors suppress delivery.

func (*Styled[T]) Opacity

func (s *Styled[T]) Opacity(a float32) *T

Opacity draws the element and its descendants at this alpha, 0..1.

func (*Styled[T]) P

func (s *Styled[T]) P(v float32) *T

func (*Styled[T]) Pb

func (s *Styled[T]) Pb(v float32) *T

func (*Styled[T]) PinLeft

func (s *Styled[T]) PinLeft(dp float32) *T

PinLeft keeps an element at an offset from its nearest ScrollX viewport's left edge. It retains layout space and paints above unpinned siblings.

func (*Styled[T]) PinRight

func (s *Styled[T]) PinRight(dp float32) *T

PinRight is PinLeft relative to the right edge.

func (*Styled[T]) Pl

func (s *Styled[T]) Pl(v float32) *T

func (*Styled[T]) Pr

func (s *Styled[T]) Pr(v float32) *T

func (*Styled[T]) Pt

func (s *Styled[T]) Pt(v float32) *T

func (*Styled[T]) Px

func (s *Styled[T]) Px(v float32) *T

func (*Styled[T]) Py

func (s *Styled[T]) Py(v float32) *T

func (*Styled[T]) Reveal

func (s *Styled[T]) Reveal(fraction float32) *T

Reveal exposes a fraction of this element's natural height, clipping both painting and input. Children retain their full layout, so text does not reflow vertically during an expand/collapse animation. NaN becomes zero.

func (*Styled[T]) Right

func (s *Styled[T]) Right(dp float32) *T

func (*Styled[T]) Role

func (s *Styled[T]) Role(role string) *T

Role sets the role agents see, e.g. "tab", "row", "option", "dialog".

func (*Styled[T]) Rounded

func (s *Styled[T]) Rounded(dp float32) *T

Rounded rounds the corners by dp; backgrounds, borders and hit areas follow.

func (*Styled[T]) RoundedCorners

func (s *Styled[T]) RoundedCorners(topLeft, topRight, bottomRight, bottomLeft float32) *T

RoundedCorners rounds each corner separately, in dp: top left, top right, bottom right, bottom left. Joined controls, such as a button group, use it to round only their outer corners. A later Rounded makes them uniform again.

func (*Styled[T]) Row

func (s *Styled[T]) Row() *T

Row lays children out left to right. The default is top to bottom.

func (*Styled[T]) ScrollOffset

func (s *Styled[T]) ScrollOffset(x, y float32) *T

ScrollOffset controls absolute x/y offsets in dp for ScrollX/ScrollY. Offsets are clamped at paint time, including disabled frames. Omit it to allow user scrolling; when supplied, native scroll gestures and scrollbars are omitted.

func (*Styled[T]) ScrollToEndOn

func (s *Styled[T]) ScrollToEndOn(version int) *T

ScrollToEndOn scrolls a ScrollY container to the end whenever version changes, and resumes StickToBottom: pass the number of messages so that sending one jumps to it even after the user scrolled up to read.

func (*Styled[T]) ScrollX

func (s *Styled[T]) ScrollX() *T

ScrollX clips and scrolls children horizontally. Set W or constrain the width through the parent. ScrollX and ScrollY can be combined.

func (*Styled[T]) ScrollY

func (s *Styled[T]) ScrollY() *T

ScrollY clips the children and scrolls them vertically. The element needs a definite height: set H, or let it Grow in a column.

func (*Styled[T]) Scrollbars

func (s *Styled[T]) Scrollbars(mode ScrollbarMode) *T

Scrollbars selects the display mode for this ScrollX/ScrollY element. Invalid modes are ignored. Hidden bars have no pointer hit area; scrolling and keyboard navigation remain available. ScrollOffset still hides all bars. Elements without a mode use SetScrollbarDefault's.

func (*Styled[T]) Selected

func (s *Styled[T]) Selected(v bool) *T

Selected reports a selected or checked state to agents.

func (*Styled[T]) Shadow

func (s *Styled[T]) Shadow(e theme.Elevation) *T

Shadow lifts the element with a soft shadow below it, in theme.Shadow's color: theme.ElevationMd for popovers and menus, ElevationLg for dialogs. The shadow is drawn outside the element and does not change its size.

func (*Styled[T]) Size

func (s *Styled[T]) Size(l Length) *T

func (*Styled[T]) StickToBottom

func (s *Styled[T]) StickToBottom() *T

StickToBottom keeps a ScrollY container scrolled to the end while content grows, as long as the user has not scrolled away from the end: a chat that follows a streaming answer but lets the user read back.

func (*Styled[T]) TabIndex

func (s *Styled[T]) TabIndex(index int) *T

TabIndex orders stops by ascending index, with tree order breaking ties. Negative indexes skip Tab traversal. The default index is zero.

func (*Styled[T]) TabStop

func (s *Styled[T]) TabStop(on bool) *T

TabStop controls sequential Tab traversal without disabling pointer/programmatic focus. Explicit Tab configuration is scoped to this el root and its active trap.

func (*Styled[T]) TextAlign

func (s *Styled[T]) TextAlign(a Align) *T

TextAlign sets alignment within wrapped text. Descendants inherit it. Start, Center and End are accepted; other values leave the style unchanged.

func (*Styled[T]) TextColor

func (s *Styled[T]) TextColor(c color.NRGBA) *T

func (*Styled[T]) TextSize

func (s *Styled[T]) TextSize(sp float32) *T

func (*Styled[T]) Top

func (s *Styled[T]) Top(dp float32) *T

func (*Styled[T]) Translate

func (s *Styled[T]) Translate(x, y float32) *T

Translate moves painting, hit areas and anchors by dp without changing layout.

func (*Styled[T]) Value

func (s *Styled[T]) Value(v string) *T

Value reports a value with the role, e.g. "40%" for a progressbar.

func (*Styled[T]) W

func (s *Styled[T]) W(l Length) *T

func (*Styled[T]) WFull

func (s *Styled[T]) WFull() *T

WFull and HFull fill the parent's content box.

func (*Styled[T]) When

func (s *Styled[T]) When(cond bool, fn func(*T)) *T

When applies fn to the element if cond holds, without breaking the chain.

func (*Styled[T]) Wrap

func (s *Styled[T]) Wrap() *T

Wrap lays children left to right and starts a new line when width runs out. Gap applies between items and lines; Grow distributes space within each line.

func (*Styled[T]) WrapFit

func (s *Styled[T]) WrapFit() *T

WrapFit wraps like Wrap but hugs each line's content when width is automatic. An explicit or stretched width retains normal per-line alignment and Grow.

type TextEl

type TextEl struct{ Styled[TextEl] }

TextEl is a run of text. It wraps to the available width.

func Text

func Text(s string) *TextEl

Text creates a text element; style it like any element (TextColor, TextSize, Bold) or let it inherit from its parent.

func (*TextEl) Ranges

func (t *TextEl) Ranges(ranges ...TextRange) *TextEl

Ranges copies color ranges without changing text measurement or shaping. Shimmer, when present, takes precedence over ranges.

func (*TextEl) Shimmer

func (t *TextEl) Shimmer(phase, spread float32, highlight color.NRGBA) *TextEl

Shimmer paints a highlight across the glyphs, preserving inherited typography. Phase is the sweep position (0..1); spread is its half-width relative to the text box (0..1). This paint-only primitive does not schedule animation.

type TextRange

type TextRange struct {
	Start, End int
	Color      color.NRGBA
}

TextRange colors a half-open Unicode rune interval. Later ranges take priority. Any overlapping shaping cluster is colored as a whole; bitmap glyphs keep their colors.

type View

type View interface {
	Render(cx *Context) Element
}

View is anything that renders an element tree: usually a struct holding the state of a screen, whose event handlers change its fields directly.

type Counter struct{ n int }

func (c *Counter) Render(cx *el.Context) el.Element {
	return el.Div().Child(el.Text(strconv.Itoa(c.n)), el.Div().OnClick(func() { c.n++ }).Child(el.Text("+1")))
}

Render runs every frame, after event handlers, under the UI lock (see ui/core). Code on other goroutines changes views through core.Update.

type ViewFunc

type ViewFunc func(*Context) Element

ViewFunc adapts a render function to a View.

func (ViewFunc) Render

func (f ViewFunc) Render(cx *Context) Element

type WidgetEl

type WidgetEl struct{ Styled[WidgetEl] }

WidgetEl wraps any core.Widget, such as Gio code wrapped in core.Func.

func Widget

func Widget(w core.Widget) *WidgetEl

Widget embeds w. It is laid out with the element's box as its constraints.

Jump to

Keyboard shortcuts

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