Documentation
¶
Overview ¶
Package ui builds user interfaces that MyGo draws itself, on the GPU where it can, for windows that show no web page:
type counter struct{ n int }
func (s *counter) view(c *ui.Context) {
ui.Column(c).Fill().Center().Gap(12).Children(func() {
ui.Text(c, fmt.Sprint(s.n)).FontSize(40).Bold()
if ui.PrimaryButton(c, "Increment").Clicked() {
s.n++
}
})
}
mygo.NewWindow(mygo.WindowOptions{Title: "Counter", Content: ui.View(s.view)})
A view is a function of the app's state that builds the interface of one frame on the main thread; MyGo calls it again after input, after Window.Update or Invalidate, and while something animates. Elements lay out their children with flexbox or in a Grid, take their colors from a Theme that follows the system's appearance, and answer questions about input, such as Clicked, where they are built. What an element keeps between frames (focus, scrolling, text being edited, animations) follows its position among its siblings, or its Key. Constructors return checked Element values that expire before the next build pass; one frame can contain several passes. Keep elements and custom parts out of app state and background goroutines. Handle provides persistent control identity for focus, commands and committed bounds; FocusBind connects desired focus to app data, and FocusedValue reads actual focus.
Views receive a stable *Context for their window, with its parent scope changing inside Children callbacks. Capture Services for persistent clipboard/URL callbacks and background redraws instead of storing Context. A control takes the user's input as its constructor returns, as Dear ImGui's and egui's widgets do: what it binds, a local copy too, holds the edit when the next statement reads it, and inline actions see the edits of the controls built before them. A container takes its input with its children, as the call that built it returns. Input follows the options of the frame the user acted on: Disabled, ReadOnly or Step set in a build govern the input of the frames after it. Changed and Submitted report input; OnClick, OnShortcut, OnChange and OnSubmit run after construction, before the rebuild. Input queries such as Clicked remain available.
Widgets take the theme's look, whose Spacing sizes them all. Each is built on a base without a look, such as ButtonBase, CheckboxBase, TabsBase or SelectBase, which handles the pointer, the keyboard, the focus and accessibility: style its elements for a design of your own.
Tester runs views in tests, without a window.
Index ¶
- Constants
- Variables
- func AlertDialog(c *Context, open *bool, title string, message string, buttons ...string) int
- func DataDragOver(e Element, options transfer.DropOptions) (transfer.Offer, bool)
- func DragOver[T any](e Element) (T, bool)
- func Drop[T any](e Element) (T, bool)
- func DropData(e Element, options transfer.DropOptions) (transfer.Drop, bool)
- func EaseIn(t float32) float32
- func EaseInOut(t float32) float32
- func EaseOut(t float32) float32
- func FocusedValue[T comparable](c *Context, field *T) T
- func ImageSize(src ImageSource) (w, h float32)
- func Linear(t float32) float32
- func Local[T any](e Element, key any, init func() T) *T
- func Nearest(points ...Point) func(Point) Point
- func Overlay(c *Context, fn func())
- func Project(value, velocity float32) float32
- func RegisterFont(data []byte, family string) error
- func Render(view func(c *Context), width int, height int, scale float32) *image.RGBA
- func Rubberband(value, lo, hi, dimension float32) float32
- func SafeToOpen(url string) bool
- func UTF16ByteOffset(s string, index int) int
- func UTF16Len(s string) int
- type AccessInfo
- type AccordionParts
- type Align
- type Anchor
- type Animation
- type AutoComplete
- type Bitmap
- type BorderStyle
- type Canvas
- type CellsStyle
- type CheckState
- type CollapsibleParts
- type Color
- type ColumnRange
- type ComboboxParts
- func (_handle ComboboxParts) Chosen() (string, bool)
- func (_handle ComboboxParts) Filtering() bool
- func (_handle ComboboxParts) Item(value string) Element
- func (_handle ComboboxParts) Open() bool
- func (_handle ComboboxParts) Popup(fn func(panel Element)) Element
- func (_handle ComboboxParts) SetOpen(o bool)
- type ConicGradient
- type Content
- type ContentTransition
- type Context
- func (_handle *Context) AddToast(t Toast) string
- func (_handle *Context) After(d time.Duration)
- func (_handle *Context) AnimationFrame()
- func (_handle *Context) Announce(text string)
- func (_handle *Context) CloseToast(id string)
- func (_handle *Context) Direction() Direction
- func (_handle *Context) DisableAnimations()
- func (_handle *Context) FocusTakesText() bool
- func (c *Context) FocusWithin(ref Handle) bool
- func (c *Context) Focused(ref Handle) bool
- func (_handle *Context) Instant() bool
- func (c *Context) Invalidate()
- func (c *Context) Key(key any) *Context
- func (_handle *Context) KeyDown(key Key) bool
- func (_handle *Context) KeysDown() []Key
- func (_handle *Context) Locale() string
- func (_handle *Context) MeasureText(width float32, spans ...Span) (float32, float32)
- func (_handle *Context) MenuPresentation() MenuPresentation
- func (_handle *Context) Modifiers() Modifiers
- func (_handle *Context) Now() time.Time
- func (c *Context) OnShortcut(mods Modifiers, key Key, fn func())
- func (c *Context) OnWindowShortcut(mods Modifiers, key Key, fn func())
- func (_handle *Context) OpenURL(url string)
- func (_handle *Context) OpenURLThen(url string, done func(err error))
- func (_handle *Context) PixelsPerDIP() float32
- func (_handle *Context) Preferences() Preferences
- func (_handle *Context) ReadClipboard() string
- func (_handle *Context) Region() i18n.Region
- func (c *Context) Resolve(ref Handle) Element
- func (_handle *Context) Root() Element
- func (_handle *Context) Router() *Router
- func (c *Context) Services() Services
- func (_handle *Context) SetMenuPresentation(p MenuPresentation)
- func (_handle *Context) SetTheme(t *Theme)
- func (_handle *Context) SetZoom(z float32)
- func (_handle *Context) Shortcut(mods Modifiers, key Key) bool
- func (_handle *Context) ShortcutRepeated() bool
- func (_handle *Context) Size() (float32, float32)
- func (_handle *Context) Theme() *Theme
- func (_handle *Context) TitleBar() TitleBar
- func (_handle *Context) Toast(message string)
- func (_handle *Context) ToastAction(message string, label string, action func())
- func (c *Context) Valid() bool
- func (_handle *Context) Vibrancy() bool
- func (_handle *Context) WindowActive() bool
- func (_handle *Context) WindowHidden() bool
- func (_handle *Context) WriteClipboard(s string)
- func (_handle *Context) WriteClipboardThen(s string, done func(err error))
- func (_handle *Context) Zoom() float32
- type Current
- type Cursor
- type Direction
- type DraggableOptions
- type Easing
- type Effect
- type EffectBackdrop
- type Element
- func Accordion(c *Context, fn func()) Element
- func AccordionItem(c *Context, title string, open *bool, fn func()) Element
- func Autocomplete(c *Context, value *string, suggestions []string) Element
- func Avatar(c *Context, name string, image *Bitmap) Element
- func BackButton(c *Context, r *Router) Element
- func Badge(c *Context, text string) Element
- func Box(c *Context) Element
- func Breadcrumbs(c *Context, items []string, chosen *int) Element
- func Button(c *Context, label string) Element
- func ButtonBase(c *Context) Element
- func Calendar(c *Context, date *time.Time) Element
- func Checkbox(c *Context, checked *bool, label string) Element
- func CheckboxBase(c *Context, checked *bool) Element
- func CheckboxGroup(c *Context, label string, fn func()) Element
- func CheckboxState(c *Context, state *CheckState, label string) Element
- func CheckboxStateBase(c *Context, state *CheckState) Element
- func Collapsible(c *Context, label string, open *bool, fn func()) Element
- func ColorPicker(c *Context, color *Color) Element
- func ColorWell(c *Context, color *Color) Element
- func Column(c *Context) Element
- func Combobox(c *Context, selected *string, options []string) Element
- func DateInput(c *Context, date *time.Time) Element
- func DecimalInput(c *Context, value *string, lo string, hi string, step string) Element
- func DialogBase(c *Context, open *bool, fn func(backdrop Element, panel Element)) Element
- func Divider(c *Context) Element
- func EditableText(c *Context, value *string) Element
- func Field(c *Context, label string, fn func()) Element
- func Fieldset(c *Context, legend string, fn func()) Element
- func FindBar(c *Context, open *bool, query *string, matches int, current *int) Element
- func Form(c *Context, fn func()) Element
- func ForwardButton(c *Context, r *Router) Element
- func Grid(c *Context) Element
- func GridView(c *Context, s *GridState, n int, minWidth float32, height float32, ...) Element
- func Icon(c *Context, s *SVG) Element
- func Image(c *Context, src ImageSource) Element
- func Link(c *Context, label string, url string) Element
- func List(c *Context, s *ListState, n int, row ...func(int)) Element
- func MenuButton(c *Context, label string, build func(m *Menu)) Element
- func Meter(c *Context, value float64, lo float64, hi float64, levels *MeterLevels) Element
- func Modal(c *Context, open *bool, fn func()) Element
- func NumberInput(c *Context, value *float64, lo float64, hi float64, step float64) Element
- func Outline[K comparable](c *Context, s *OutlineState[K], roots []K, children func(arg0 K) []K, ...) Element
- func OutlineTable[K comparable](c *Context, s *OutlineState[K], columns []TableColumn, roots []K, ...) Element
- func Popover(c *Context, anchor Element, open *bool, fn func()) Element
- func PopoverBase(c *Context, anchor Element, open *bool, fn func(panel Element)) Element
- func PopoverMenuButton(c *Context, label string, build func(m *Menu), ...) Element
- func PrimaryButton(c *Context, label string) Element
- func Progress(c *Context, value float64) Element
- func Radio[T comparable](c *Context, selected *T, value T, label string) Element
- func RadioBase[T comparable](c *Context, selected *T, value T) Element
- func RadioGroup(c *Context, fn func()) Element
- func RangeSlider(c *Context, low *float64, high *float64, lo float64, hi float64, step float64) Element
- func Rating(c *Context, value *int, max int) Element
- func RichText(c *Context, spans ...Span) Element
- func Row(c *Context) Element
- func Scroll(c *Context) Element
- func ScrollBoth(c *Context) Element
- func ScrollHorizontal(c *Context) Element
- func SearchField(c *Context, query *string) Element
- func Segmented(c *Context, selected *int, labels ...string) Element
- func Select(c *Context, selected *string, options []string) Element
- func Sidebar(c *Context, selected *string, fn func()) Element
- func SidebarItem(c *Context, id string, icon *SVG, label string) Element
- func SidebarSection(c *Context, title string, open *bool, fn func()) Element
- func Slider(c *Context, value *float64, lo float64, hi float64) Element
- func SliderBase(c *Context, value *float64, lo float64, hi float64) Element
- func Spacer(c *Context) Element
- func Spinner(c *Context) Element
- func Split(c *Context, size *float32, first func(), second func()) Element
- func SplitPercent(c *Context, p *float32, first func(), second func()) Element
- func SplitVertical(c *Context, size *float32, first func(), second func()) Element
- func SplitVerticalPercent(c *Context, p *float32, first func(), second func()) Element
- func StepSlider(c *Context, value *float64, lo float64, hi float64, step float64) Element
- func Stepper(c *Context, value *float64, lo float64, hi float64, step float64) Element
- func Switch(c *Context, on *bool) Element
- func SwitchBase(c *Context, on *bool) Element
- func Table(c *Context, s *ListState, columns []TableColumn, n int, ...) Element
- func Tabs(c *Context, selected *int, labels ...string) Element
- func Text(c *Context, s string) Element
- func TextArea(c *Context, value *string) Element
- func TextAreaBase(c *Context, value *string) Element
- func TextAreaBuffer(c *Context, value *TextBuffer) Element
- func TextAreaBufferBase(c *Context, value *TextBuffer) Element
- func TextInput(c *Context, value *string) Element
- func TextInputBase(c *Context, value *string) Element
- func TextInputBuffer(c *Context, value *TextBuffer) Element
- func TextInputBufferBase(c *Context, value *TextBuffer) Element
- func Textf(c *Context, format string, args ...any) Element
- func Themed(c *Context, t *Theme) Element
- func TimeInput(c *Context, tm *time.Time) Element
- func ToastViewportBase(c *Context, fn func(viewport Element, toasts []Toast)) Element
- func Toggle(c *Context, on *bool, label string) Element
- func ToggleBase(c *Context, on *bool) Element
- func ToggleGroup(c *Context, fn func()) Element
- func TokenField(c *Context, tokens *[]string, suggestions []string) Element
- func Toolbar(c *Context, fn func()) Element
- func TooltipBase(c *Context, anchor Element, fn func(tip Element)) Element
- func Tree(c *Context, fn func()) Element
- func TreeItem(c *Context, label string, open *bool, children func()) Element
- func Video(c *Context, p *VideoPlayer) Element
- func WebView(c *Context, v NativeWebView) Element
- func (_handle Element) Absolute() Element
- func (_handle Element) Access(fn func(n *platform.AccessNode)) Element
- func (_handle Element) AccessDisabled(off bool) Element
- func (_handle Element) AccessHidden(hide bool) Element
- func (_handle Element) AccessSelected(on bool) Element
- func (_handle Element) ActiveDescendant(d Element) Element
- func (_handle Element) AlignContent(a Align) Element
- func (_handle Element) AlignItems(a Align) Element
- func (_handle Element) AlignSelf(a Align) Element
- func (_handle Element) Animate(key any, target float32, d time.Duration) float32
- func (_handle Element) AnimateColor(key any, target Color, a Animation) Color
- func (_handle Element) AnimatePose(p Pose, a Animation) Element
- func (_handle Element) AnimateTo(key any, target float32, a Animation) float32
- func (_handle Element) AnimateWith(key any, target float32, d time.Duration, ease Easing) float32
- func (_handle Element) Arrived(key any) bool
- func (_handle Element) AspectRatio(r float32) Element
- func (_handle Element) Attach(at Anchor, self Anchor) Element
- func (_handle Element) AttachEdgeMargin(v float32) Element
- func (_handle Element) AttachTo(target Element, at Anchor, self Anchor) Element
- func (_handle Element) AttachedAnchors() (Anchor, Anchor)
- func (_handle Element) AttachedOrigin() Element
- func (_handle Element) AutoComplete(kind AutoComplete) Element
- func (_handle Element) AutoFocus() Element
- func (_handle Element) BackfaceHidden() Element
- func (_handle Element) Background(c Color) Element
- func (_handle Element) Balance() Element
- func (_handle Element) Basis(v float32) Element
- func (_handle Element) BasisPercent(p float32) Element
- func (e Element) Bind(r *Handle) Element
- func (_handle Element) Blur(sigma float32) Element
- func (_handle Element) Bold() Element
- func (_handle Element) Border(width float32, c Color) Element
- func (_handle Element) BorderColor(c Color) Element
- func (_handle Element) BorderConicGradient(g ConicGradient) Element
- func (_handle Element) BorderEndWidth(v float32) Element
- func (_handle Element) BorderLinearGradient(g LinearGradient) Element
- func (_handle Element) BorderStartWidth(v float32) Element
- func (_handle Element) BorderStyle(s BorderStyle) Element
- func (_handle Element) BorderWidth(v ...float32) Element
- func (_handle Element) Bottom(v float32) Element
- func (_handle Element) BottomPercent(p float32) Element
- func (_handle Element) Bounds() Rect
- func (_handle Element) Browse() Element
- func (_handle Element) Busy(on bool) Element
- func (_handle Element) Cache() Element
- func (_handle Element) CaretColor(c Color) Element
- func (_handle Element) CaretWidth(width float32) Element
- func (_handle Element) Center() Element
- func (_handle Element) Changed() bool
- func (_handle Element) Checked(on bool) Element
- func (_handle Element) ChildExit(m Motion) Element
- func (e Element) Children(fn func()) Element
- func (_handle Element) ClickModifiers() Modifiers
- func (_handle Element) Clicked() bool
- func (_handle Element) Clicks() int
- func (_handle Element) Clip() Element
- func (_handle Element) ClipInset(top float32, right float32, bottom float32, left float32, radius float32) Element
- func (_handle Element) ClipInsetPercent(top float32, right float32, bottom float32, left float32, radius float32) Element
- func (_handle Element) ClipX() Element
- func (_handle Element) ClipY() Element
- func (_handle Element) Column() Element
- func (_handle Element) ColumnCount(n int) Element
- func (_handle Element) ColumnIndex(i int) Element
- func (_handle Element) ColumnSpan(n int) Element
- func (_handle Element) ColumnStart(n int) Element
- func (_handle Element) ColumnTracks(tracks ...Track) Element
- func (_handle Element) Columns(n int) Element
- func (_handle Element) Composing() bool
- func (_handle Element) ConicGradient(g ConicGradient) Element
- func (_handle Element) ContentTransition(t ContentTransition) Element
- func (_handle Element) ContextMenu(build func(m *Menu)) Element
- func (_handle Element) Controls(target Element) Element
- func (_handle Element) CopyData(fn func(parts []SelectedText) transfer.Data) Element
- func (_handle Element) Current(kind Current) Element
- func (_handle Element) Cursor(c Cursor) Element
- func (_handle Element) Debug() Element
- func (_handle Element) DecorationColor(c Color) Element
- func (_handle Element) DecorationThickness(v float32) Element
- func (_handle Element) DescribedBy(desc Element) Element
- func (_handle Element) Description(s string) Element
- func (_handle Element) DimDisabled(dim bool) Element
- func (_handle Element) Direction(d Direction) Element
- func (_handle Element) Disabled(d bool) Element
- func (_handle Element) Dismissed() bool
- func (_handle Element) Dividers(width float32, c Color) Element
- func (_handle Element) DottedUnderline() Element
- func (_handle Element) DoubleClicked() bool
- func (_handle Element) Drag(value any) Element
- func (_handle Element) DragData(data transfer.Data, options ...transfer.DragOptions) Element
- func (_handle Element) DragDataFrom(data func() transfer.Data, options ...transfer.DragOptions) Element
- func (_handle Element) DragEnded() (float32, float32, bool)
- func (_handle Element) DragMissed() (Point, bool)
- func (_handle Element) DragOffset() Point
- func (_handle Element) DragVelocity() (float32, float32)
- func (_handle Element) DragWindow() Element
- func (_handle Element) Draggable(offset *Point, o DraggableOptions) Element
- func (_handle Element) Dragged() (float32, float32, bool)
- func (_handle Element) Dragging() bool
- func (_handle Element) Draw(fn func(p *Painter, r Rect)) Element
- func (_handle Element) DrawObjects(fn func(p *Painter, at int, r Rect)) Element
- func (_handle Element) DrawOver(fn func(p *Painter, r Rect)) Element
- func (_handle Element) DroppedFiles() []string
- func (_handle Element) Effect(fx Effect) Element
- func (_handle Element) Ellipsis(s string) Element
- func (_handle Element) End(v float32) Element
- func (_handle Element) EndPercent(p float32) Element
- func (_handle Element) Error(msg string) Element
- func (_handle Element) ErrorMessage(msg Element) Element
- func (_handle Element) Expanded(open bool) Element
- func (_handle Element) FileDragOver() bool
- func (_handle Element) Fill() Element
- func (_handle Element) FillHeight() Element
- func (_handle Element) FillWidth() Element
- func (_handle Element) Fit(f Fit) Element
- func (_handle Element) FixedLineHeight(v float32) Element
- func (_handle Element) Focus() Element
- func (e Element) FocusBind(field any, value any) Element
- func (_handle Element) FocusGroup(o Orientation) Element
- func (_handle Element) FocusLeft() bool
- func (_handle Element) FocusRing(show bool) Element
- func (_handle Element) FocusRingColor(color Color) Element
- func (_handle Element) FocusRingOffset(d float32) Element
- func (_handle Element) FocusVisible() bool
- func (_handle Element) FocusWithin() bool
- func (_handle Element) Focusable() Element
- func (_handle Element) Focused() bool
- func (_handle Element) Font(family string) Element
- func (_handle Element) FontFeatures(features ...string) Element
- func (_handle Element) FontSize(v float32) Element
- func (_handle Element) FontWeight(w int) Element
- func (_handle Element) Gap(v float32) Element
- func (_handle Element) GapX(v float32) Element
- func (_handle Element) GapY(v float32) Element
- func (_handle Element) Gradient(from Color, to Color, angle float32) Element
- func (_handle Element) Grayscale() Element
- func (_handle Element) Grid() Element
- func (_handle Element) GridRows(n int) Element
- func (_handle Element) Grow(f float32) Element
- func (_handle Element) HandleInput(fn func(ev InputEvent) bool) Element
- func (_handle Element) HandleTextInput(client TextInputClient) Element
- func (_handle Element) HasPopup(kind Popup) Element
- func (_handle Element) Height(v float32) Element
- func (_handle Element) HeightPercent(p float32) Element
- func (_handle Element) Hidden(hide bool) Element
- func (_handle Element) Highlighted() bool
- func (_handle Element) HitTest(fn func(x float32, y float32, r Rect) bool) Element
- func (_handle Element) HostLayer(layer *UILayer, surface SurfaceMap) Element
- func (_handle Element) Hovered() bool
- func (_handle Element) ID() uint64
- func (_handle Element) IgnoreInput(ignore bool) Element
- func (_handle Element) InView() bool
- func (_handle Element) InViewAmount(amount float32, margin ...float32) bool
- func (_handle Element) InViewMargin(margin ...float32) bool
- func (_handle Element) InputMethod(on bool) Element
- func (_handle Element) InsetShadow(x float32, y float32, blur float32, spread float32, c Color) Element
- func (_handle Element) Invalid(on bool) Element
- func (_handle Element) Invisible() Element
- func (_handle Element) IsDisabled() bool
- func (_handle Element) Italic() Element
- func (e Element) ItemKey(key func(int) any) Element
- func (_handle Element) Jump(key any, value float32) float32
- func (_handle Element) Justify(a Align) Element
- func (_handle Element) JustifyItems(a Align) Element
- func (_handle Element) JustifySelf(a Align) Element
- func (_handle Element) KeepFocus() Element
- func (_handle Element) KeepOpen() Element
- func (_handle Element) KeepScrollbars(keep bool) Element
- func (e Element) Key(key any) Element
- func (_handle Element) KeyShortcuts(mods Modifiers, key Key) Element
- func (_handle Element) Keyframes(key any, frames []Keyframe, options ...KeyframeOptions) float32
- func (_handle Element) Label(s string) Element
- func (_handle Element) LabelledBy(label Element) Element
- func (_handle Element) Lang(tag string) Element
- func (_handle Element) LayoutBounds() Rect
- func (_handle Element) Left(v float32) Element
- func (_handle Element) LeftPercent(p float32) Element
- func (_handle Element) LetterSpacing(v float32) Element
- func (_handle Element) Level(n int) Element
- func (_handle Element) LineHeight(m float32) Element
- func (_handle Element) LinearGradient(g LinearGradient) Element
- func (_handle Element) Lines(min int, max int) Element
- func (_handle Element) LocalToWindow(x float32, y float32) (float32, float32)
- func (_handle Element) Loop(key any, period time.Duration, ease Easing) float32
- func (_handle Element) Margin(v ...float32) Element
- func (_handle Element) MarginEnd(v float32) Element
- func (_handle Element) MarginStart(v float32) Element
- func (_handle Element) MarginX(v float32) Element
- func (_handle Element) MarginY(v float32) Element
- func (_handle Element) MaskConicGradient(g ConicGradient) Element
- func (_handle Element) MaskLinearGradient(g LinearGradient) Element
- func (_handle Element) MaskRadialGradient(g RadialGradient) Element
- func (_handle Element) Masks(layers ...Mask) Element
- func (e Element) Material(m Material) Element
- func (_handle Element) MaxHeight(v float32) Element
- func (_handle Element) MaxHeightPercent(p float32) Element
- func (_handle Element) MaxLength(n int) Element
- func (_handle Element) MaxLines(n int) Element
- func (_handle Element) MaxWidth(v float32) Element
- func (_handle Element) MaxWidthPercent(p float32) Element
- func (_handle Element) MaximizeButton() Element
- func (_handle Element) Menu(build func(m *Menu)) Element
- func (_handle Element) MinHeight(v float32) Element
- func (_handle Element) MinHeightPercent(p float32) Element
- func (_handle Element) MinWidth(v float32) Element
- func (_handle Element) MinWidthPercent(p float32) Element
- func (_handle Element) Mixed() Element
- func (_handle Element) Modal() Element
- func (_handle Element) Multiselectable(on bool) Element
- func (_handle Element) NoShadow() Element
- func (_handle Element) NoWrap() Element
- func (_handle Element) ObjectPosition(x float32, y float32) Element
- func (_handle Element) ObserveInput(fn func(ev InputEvent)) Element
- func (e Element) OnChange(fn func()) Element
- func (e Element) OnClick(fn func()) Element
- func (_handle Element) OnPaste(fn func(text string) bool) Element
- func (e Element) OnShortcut(mods Modifiers, key Key, fn func()) Element
- func (e Element) OnSubmit(fn func()) Element
- func (_handle Element) OnTextKey(fn func(k TextKey) bool) Element
- func (_handle Element) Opacity(o float32) Element
- func (_handle Element) Orientation(o Orientation) Element
- func (_handle Element) OverlayShortcut(mods Modifiers, key Key) bool
- func (_handle Element) Padding(v ...float32) Element
- func (_handle Element) PaddingEnd(v float32) Element
- func (_handle Element) PaddingStart(v float32) Element
- func (_handle Element) PaddingX(v float32) Element
- func (_handle Element) PaddingY(v float32) Element
- func (_handle Element) PassThrough() Element
- func (_handle Element) Password() Element
- func (_handle Element) Perspective(distance float32) Element
- func (_handle Element) Placeholder(s string) Element
- func (_handle Element) PlaceholderColor(color Color) Element
- func (_handle Element) PointerPosition() (float32, float32, bool)
- func (_handle Element) PopoverMenu(build func(m *Menu)) Element
- func (_handle Element) PopoverMenuButton(build func(m *Menu), options ...PopoverMenuButtonOptions) Element
- func (_handle Element) PositionInSet(pos int, size int) Element
- func (_handle Element) PreserveSpaces() Element
- func (_handle Element) PressCanceled() bool
- func (_handle Element) Pressed() bool
- func (_handle Element) PressedButton() (int, bool)
- func (_handle Element) PressedInside() bool
- func (_handle Element) PressedOutside() bool
- func (_handle Element) PressedPointer() (PointerType, float32, bool)
- func (_handle Element) Pretty() Element
- func (_handle Element) RadialGradient(g RadialGradient) Element
- func (_handle Element) Radius(r ...float32) Element
- func (_handle Element) Range(lo float64, hi float64, value float64) Element
- func (_handle Element) ReadOnly(on bool) Element
- func (e Element) Ref(r *Ref) Element
- func (_handle Element) Reverse() Element
- func (_handle Element) Right(v float32) Element
- func (_handle Element) RightClicked() bool
- func (_handle Element) RightPercent(p float32) Element
- func (_handle Element) Role(r Role) Element
- func (_handle Element) RoleDescription(s string) Element
- func (_handle Element) Rotate(degrees float32) Element
- func (_handle Element) RotateX(degrees float32) Element
- func (_handle Element) RotateY(degrees float32) Element
- func (_handle Element) Row() Element
- func (_handle Element) RowCount(n int) Element
- func (_handle Element) RowDoubleClicked() bool
- func (_handle Element) RowIndex(i int) Element
- func (_handle Element) RowSpan(n int) Element
- func (_handle Element) RowStart(n int) Element
- func (_handle Element) RowTracks(tracks ...Track) Element
- func (_handle Element) RowWidth(w float32) Element
- func (e Element) Rows(row func(ListRow)) Element
- func (_handle Element) Scale(x float32, y float32) Element
- func (_handle Element) ScrollIntoView(options ...ScrollIntoViewOptions) Element
- func (_handle Element) ScrollSnap(s Snap) Element
- func (_handle Element) ScrollWith(scroller Element) Element
- func (_handle Element) ScrollbarInsets(v ...float32) Element
- func (_handle Element) Scrollbars(visible bool) Element
- func (_handle Element) Search() Element
- func (_handle Element) Selectable() Element
- func (_handle Element) Selected(on bool) Element
- func (_handle Element) SelectedTexts() []SelectedText
- func (e Element) Selection(selection Selector) Element
- func (_handle Element) SelectionColor(c Color) Element
- func (_handle Element) SetChanged() Element
- func (_handle Element) SetTextSelection(start int, end int) Element
- func (_handle Element) Settled(key any) bool
- func (_handle Element) Shadow(x float32, y float32, blur float32, spread float32, c Color) Element
- func (_handle Element) Shortcut(mods Modifiers, key Key) bool
- func (_handle Element) Shrink(f float32) Element
- func (_handle Element) SingleLine() Element
- func (_handle Element) Size(w float32, h float32) Element
- func (_handle Element) Skew(x float32, y float32) Element
- func (_handle Element) SnapAlign(a Align) Element
- func (_handle Element) SnapAlignX(a Align) Element
- func (_handle Element) SnapAlignY(a Align) Element
- func (_handle Element) Sort(dir SortDirection) Element
- func (_handle Element) SplitReset(v float32) Element
- func (_handle Element) Spring(key any, target float32, options ...SpringOptions) float32
- func (_handle Element) Start(v float32) Element
- func (_handle Element) StartPercent(p float32) Element
- func (_handle Element) Step(step float64) Element
- func (_handle Element) Sticky() Element
- func (_handle Element) Strikethrough() Element
- func (_handle Element) Stripes(c Color, width float32, gap float32, angle float32) Element
- func (_handle Element) Submitted() bool
- func (_handle Element) TabSize(n float32) Element
- func (_handle Element) TabStop(stop bool) Element
- func (_handle Element) TextAlign(a Align) Element
- func (_handle Element) TextAnchorCaret() (int, int)
- func (_handle Element) TextBackground(c Color) Element
- func (_handle Element) TextCaret(r Rect) Element
- func (_handle Element) TextColor(c Color) Element
- func (_handle Element) TextRanges(ranges ...TextRange) Element
- func (_handle Element) TextSelection() (int, int)
- func (_handle Element) TextShadow(x float32, y float32, blur float32, c Color) Element
- func (_handle Element) TextStroke(width float32, c Color) Element
- func (_handle Element) Timeline(key any, o TimelineOptions) *Timeline
- func (_handle Element) Tooltip(s string) Element
- func (_handle Element) Top(v float32) Element
- func (_handle Element) TopPercent(p float32) Element
- func (_handle Element) TrackLines(l *TextLines) Element
- func (_handle Element) TrackScroll(s *ScrollState) Element
- func (_handle Element) Transform(t Transform) Element
- func (_handle Element) TransformOrigin(x float32, y float32) Element
- func (_handle Element) Transition(t ElementTransition) Element
- func (_handle Element) Transitioning() bool
- func (_handle Element) Translate(x float32, y float32) Element
- func (_handle Element) TranslatePercent(x float32, y float32) Element
- func (_handle Element) TranslateZ(z float32) Element
- func (_handle Element) Underline() Element
- func (_handle Element) UnderlineOffset(v float32) Element
- func (_handle Element) Unselectable() Element
- func (e Element) Valid() bool
- func (_handle Element) Value(s string) Element
- func (_handle Element) Velocity(key any) float32
- func (_handle Element) Vertical() Element
- func (_handle Element) WavyUnderline() Element
- func (_handle Element) Width(v float32) Element
- func (_handle Element) WidthPercent(p float32) Element
- func (_handle Element) WindowToLocal(x float32, y float32) (float32, float32, bool)
- func (_handle Element) Wrap() Element
- func (_handle Element) WrapReverse() Element
- func (_handle Element) ZIndex(z int) Element
- type ElementTransition
- type FillRule
- type Fit
- type Font
- type FontFamily
- type FontMetrics
- type GPUTexture
- type Glyph
- type GradientStop
- type GridState
- type Handle
- func (r Handle) Bounds(c *Context) Rect
- func (r *Handle) CancelFocus(window ...*Context)
- func (r *Handle) Focus(window ...*Context)
- func (r Handle) FocusWithin(c *Context) bool
- func (r Handle) Focused(c *Context) bool
- func (r Handle) HandleLayerInput(c *Context, ev InputEvent) bool
- func (r *Handle) OnShortcut(c *Context, mods Modifiers, key Key, fn func())
- func (r *Handle) RequestFocus(window ...*Context)
- type ImageOptions
- type ImageSource
- type InputEvent
- type InputKind
- type Key
- type KeyCode
- type Keyframe
- type KeyframeOptions
- type LineCap
- type LineJoin
- type LinearGradient
- type ListRow
- type ListState
- func (s *ListState) AtEnd() bool
- func (s *ListState) CellSelected(row, col int) bool
- func (s *ListState) DragSelecting() bool
- func (s *ListState) ExtendTo(row int)
- func (_handle *ListState) Focus(c *Context) bool
- func (_handle *ListState) FocusWithin(c *Context) bool
- func (_handle *ListState) Focused(c *Context) bool
- func (s *ListState) HoldPlace()
- func (s *ListState) ScrollIntoView(row int)
- func (s *ListState) ScrollTo(row int, align Align)
- func (s *ListState) ScrollToEnd()
- func (s *ListState) SelectColumns(from, to string)
- func (s *ListState) SelectedColumns() []string
- func (_handle *ListState) Shortcut(c *Context, mods Modifiers, key Key) bool
- func (s *ListState) Visible() (first, last int)
- type Mask
- type MaskBox
- type MaskComposite
- type MaskImage
- type Material
- type MaterialBuilder
- type Menu
- type MenuIcon
- type MenuItem
- func (it *MenuItem) Checked(on bool) *MenuItem
- func (it *MenuItem) Chosen() bool
- func (it *MenuItem) Content(fn func(content MenuItemContent)) *MenuItem
- func (it *MenuItem) Danger() *MenuItem
- func (it *MenuItem) Disabled(d bool) *MenuItem
- func (it *MenuItem) Highlighted() bool
- func (it *MenuItem) ID(id string) *MenuItem
- func (it *MenuItem) Icon(icon MenuIcon) *MenuItem
- func (it *MenuItem) IconColor(c Color) *MenuItem
- func (it *MenuItem) Radio(on bool) *MenuItem
- func (it *MenuItem) Shortcut(mods Modifiers, key Key) *MenuItem
- func (it *MenuItem) Subtitle(s string) *MenuItem
- func (it *MenuItem) Tooltip(s string) *MenuItem
- func (it *MenuItem) Trailing(s string) *MenuItem
- type MenuItemContent
- type MenuParts
- func (_handle MenuParts) CheckItem(checked bool) Element
- func (_handle MenuParts) Group(fn func(group Element)) Element
- func (_handle MenuParts) Item() Element
- func (_handle MenuParts) Open() bool
- func (_handle MenuParts) Popup(fn func(panel Element)) Element
- func (_handle MenuParts) RadioItem(selected bool) Element
- func (_handle MenuParts) Submenu(item Element, fn func(panel Element))
- func (_handle MenuParts) SubmenuItem() Element
- type MenuPresentation
- type MeterLevels
- type Modifiers
- type Motion
- type NativeGlassMaterial
- type NativeGlassSpec
- type NativeWebView
- type Orientation
- type OutlineRow
- type OutlineState
- type Painter
- func (p *Painter) Accelerated() bool
- func (p *Painter) After(d time.Duration)
- func (p *Painter) AnimationFrame()
- func (p *Painter) AnimationFrameRate(fps float32)
- func (p *Painter) Clip(r Rect, radius float32, fn func())
- func (p *Painter) ClipPath(path *Path, fn func())
- func (p *Painter) Effect(fx *scene.Effect, r Rect, radii [4]float32, blur float32, params [5][4]float32)
- func (p *Painter) EffectBackdrop(r Rect, blur float32, inset Point) EffectBackdrop
- func (p *Painter) EffectColor(c Color) (srgb, wide [4]float32)
- func (p *Painter) EffectWords(n int) []uint32
- func (p *Painter) Fill(r Rect, c Color, radius float32)
- func (p *Painter) FillConicGradient(r Rect, g ConicGradient, radius float32)
- func (p *Painter) FillGradient(r Rect, g LinearGradient, radius float32)
- func (p *Painter) FillPath(path *Path, c Color)
- func (p *Painter) FillPathConicGradient(path *Path, g ConicGradient)
- func (p *Painter) FillPathGradient(path *Path, g LinearGradient)
- func (p *Painter) FillRadialGradient(r Rect, g RadialGradient, radius float32)
- func (p *Painter) FillRadii(r Rect, radii [4]float32, c Color)
- func (p *Painter) FocusRing(r Rect, radius [4]float32)
- func (p *Painter) Glyphs(glyphs []Glyph, x, y float32, c Color)
- func (p *Painter) Hole(r Rect, radii [4]float32)
- func (p *Painter) Icon(s *SVG, r Rect, c Color)
- func (p *Painter) Image(src ImageSource, r Rect, fit Fit)
- func (p *Painter) ImageRegion(b *Bitmap, src, dst Rect, o ImageOptions)
- func (p *Painter) Line(x0, y0, x1, y1, width float32, c Color)
- func (p *Painter) MeasureText(width float32, spans ...Span) (w, h float32)
- func (p *Painter) NativeGlassSupported() bool
- func (p *Painter) Now() time.Time
- func (p *Painter) Preferences() Preferences
- func (p *Painter) RichText(x, y, width float32, spans ...Span) (w, h float32)
- func (p *Painter) Scale() float32
- func (p *Painter) Scrollbar(s Scrollbar, st ScrollbarState)
- func (p *Painter) ShaderEffect(fx *scene.Effect, r Rect, radius float32, in ShaderInput)
- func (p *Painter) ShaderFill(fx *scene.Effect, box Rect, in ShaderInput, fn func())
- func (p *Painter) Shadow(r Rect, radius, x, y, blur, spread float32, c Color)
- func (p *Painter) Stroke(r Rect, c Color, radius, width float32)
- func (p *Painter) StrokeDashed(r Rect, c Color, radius, width float32)
- func (p *Painter) StrokePath(path *Path, width float32, c Color)
- func (p *Painter) StrokePathConicGradient(path *Path, width float32, g ConicGradient)
- func (p *Painter) StrokePathGradient(path *Path, width float32, g LinearGradient)
- func (p *Painter) StrokePolyline(points [][2]float32, width float32, c Color)
- func (p *Painter) Text(x, y float32, s string, size float32, c Color)
- func (p *Painter) TextLayout(layout *TextLayout, x, y float32, color Color)
- func (p *Painter) TextLine(l *text.Layout, x, y float32, color func(cluster int) Color)
- func (p *Painter) Theme() *Theme
- func (p *Painter) Transform(t Transform, ox, oy float32, fn func())
- func (p *Painter) Visible() Rect
- type Path
- func (p *Path) Bounds() Rect
- func (p *Path) Cap(c LineCap) *Path
- func (p *Path) Circle(cx, cy, r float32) *Path
- func (p *Path) Close() *Path
- func (p *Path) Contains(x, y float32) bool
- func (p *Path) CubeTo(c1x, c1y, c2x, c2y, x, y float32) *Path
- func (p *Path) Dash(offset float32, lengths ...float32) *Path
- func (p *Path) FillRule(r FillRule) *Path
- func (p *Path) Join(j LineJoin) *Path
- func (p *Path) LineTo(x, y float32) *Path
- func (p *Path) MiterLimit(limit float32) *Path
- func (p *Path) MoveTo(x, y float32) *Path
- func (p *Path) QuadTo(cx, cy, x, y float32) *Path
- func (p *Path) Reset() *Path
- func (p *Path) Trim(from, to float32) *Path
- type Placement
- type PlanarSurface
- type Point
- type PointerAccuracy
- type PointerType
- type PopoverMenuButtonOptions
- type Popup
- type Pose
- type Preferences
- type ProjectiveSurface
- func (s *ProjectiveSurface) ScreenToSurface(p Point) (SurfaceHit, bool)
- func (s *ProjectiveSurface) SetRect(rect Rect)
- func (s *ProjectiveSurface) SetTransform(t Transform)
- func (s *ProjectiveSurface) SetVersion(v uint64)
- func (s *ProjectiveSurface) SurfaceToScreen(uv UV) (Point, bool)
- func (s *ProjectiveSurface) Version() uint64
- type RadialGradient
- type Rect
- type Ref
- type Role
- type Route
- type Router
- func (r *Router) Back()
- func (r *Router) CanGoBack() bool
- func (r *Router) CanGoForward() bool
- func (r *Router) Forward()
- func (r *Router) Go(n int)
- func (r *Router) Location() string
- func (r *Router) Path() string
- func (r *Router) Push(target string)
- func (r *Router) Query(name string) string
- func (r *Router) Replace(target string)
- func (r *Router) Title() string
- func (_handle *Router) View(c *Context, fn func(r *Route)) Element
- type SVG
- type ScrollAlign
- type ScrollIntoViewOptions
- type ScrollState
- type Scrollbar
- type ScrollbarState
- type SegmentedParts
- type SelectParts
- type SelectedText
- type Selection
- type Selector
- type Services
- func (s Services) ClipboardFormats() []transfer.Format
- func (s Services) Invalidate()
- func (s Services) OpenURL(url string)
- func (s Services) ReadClipboard() string
- func (s Services) ReadClipboardData(formats ...transfer.Format) transfer.Data
- func (s Services) WriteClipboard(text string)
- func (s Services) WriteClipboardData(data transfer.Data)
- type ShaderInput
- type Snap
- type SortDirection
- type SortOrder
- type Span
- type SpringOptions
- type SurfaceHit
- type SurfaceMap
- type TableColumn
- type TableLayout
- type TabsParts
- type Tester
- func (t *Tester) Access(name string) (AccessInfo, bool)
- func (t *Tester) AccessAll() []AccessInfo
- func (t *Tester) AccessByRole(r Role, name string) (AccessInfo, bool)
- func (t *Tester) Advance(d time.Duration)
- func (t *Tester) Announcements() []string
- func (t *Tester) CancelPress()
- func (t *Tester) ChooseMenuItem(path ...string) error
- func (t *Tester) Click(s string) error
- func (t *Tester) ClickAt(x, y float32)
- func (t *Tester) ClickAtWith(mods Modifiers, x, y float32)
- func (t *Tester) ClickWith(mods Modifiers, s string) error
- func (t *Tester) Clipboard() string
- func (t *Tester) ClipboardData() transfer.Data
- func (t *Tester) CloseMenu()
- func (t *Tester) CodeDown(mods Modifiers, code KeyCode)
- func (t *Tester) CodeUp(mods Modifiers, code KeyCode)
- func (t *Tester) Command(name string)
- func (t *Tester) Compose(text string, caret int)
- func (t *Tester) Cursor() Cursor
- func (t *Tester) DropFiles(x, y float32, paths ...string) bool
- func (t *Tester) FailClipboard(err error)
- func (t *Tester) FailOpenURL(err error)
- func (t *Tester) Find(s string) (Rect, bool)
- func (t *Tester) Focused(s string) bool
- func (t *Tester) Frame()
- func (t *Tester) FramePending() bool
- func (t *Tester) HasText(s string) bool
- func (t *Tester) HoldModifiers(mods Modifiers)
- func (t *Tester) Image() *image.RGBA
- func (t *Tester) Key(mods Modifiers, key Key)
- func (t *Tester) KeyAt(mods Modifiers, physical Key)
- func (t *Tester) KeyDown(key Key)
- func (t *Tester) KeyRepeat(mods Modifiers, key Key)
- func (t *Tester) KeyUp(key Key)
- func (t *Tester) Menu() []string
- func (t *Tester) Move(x, y float32)
- func (t *Tester) Now() time.Time
- func (t *Tester) OpenedURLs() []string
- func (t *Tester) Pinch(x, y, scale float32)
- func (t *Tester) Press(x, y float32)
- func (t *Tester) PressButton(button int, x, y float32)
- func (t *Tester) Release(x, y float32)
- func (t *Tester) ReleaseButton(button int, x, y float32)
- func (t *Tester) RightClick(s string) error
- func (t *Tester) RightClickAt(x, y float32)
- func (t *Tester) Scroll(x, y, dx, dy float32)
- func (t *Tester) SetClipboard(s string)
- func (t *Tester) SetClipboardData(d transfer.Data)
- func (t *Tester) SetDark(dark bool)
- func (t *Tester) SetDirection(d Direction)
- func (t *Tester) SetFocused(focused bool)
- func (t *Tester) SetLocale(tag string)
- func (t *Tester) SetPreferences(p Preferences)
- func (t *Tester) SetRegion(r i18n.Region)
- func (t *Tester) SetScale(scale float32)
- func (t *Tester) SetSize(width, height int)
- func (t *Tester) SetTitleBar(bar TitleBar)
- func (t *Tester) SetVibrancy(shows bool)
- func (t *Tester) SetWindowActive(active bool)
- func (t *Tester) SetWindowHidden(hidden bool)
- func (t *Tester) SetZoom(z float32)
- func (t *Tester) TextCaret() (Rect, bool)
- func (t *Tester) TextInputActive() (active, noInputMethod bool)
- func (t *Tester) Texts() []string
- func (t *Tester) Type(s string)
- func (t *Tester) TypeKey(mods Modifiers, key Key, text string)
- func (t *Tester) UsePointer(pointer PointerType, pressure float32)
- func (t *Tester) WebViewAt(x, y float32) NativeWebView
- func (t *Tester) Wheel(x, y, dx, dy float32)
- type TesterOptions
- type TextAffinity
- type TextBuffer
- func (b *TextBuffer) ByteLen() int
- func (b *TextBuffer) Len() int
- func (b *TextBuffer) LineCount() int
- func (b *TextBuffer) Replace(start, end int, s string)
- func (b *TextBuffer) ReplaceUTF16(r TextInputRange, s string) TextInputRange
- func (b *TextBuffer) Restore(s TextSnapshot)
- func (b *TextBuffer) RuneOffset(index int) int
- func (b *TextBuffer) Set(s string)
- func (b *TextBuffer) Slice(start, end int) string
- func (b *TextBuffer) Snapshot() TextSnapshot
- func (b *TextBuffer) String() string
- func (b *TextBuffer) TextForRange(r TextInputRange) (string, TextInputRange)
- func (b *TextBuffer) UTF16Len() int
- func (b *TextBuffer) UTF16Offset(index int) int
- func (b *TextBuffer) Version() uint64
- func (b *TextBuffer) WriteTo(w io.Writer) (int64, error)
- type TextCaretPosition
- type TextInputClient
- type TextInputRange
- type TextInputSelection
- type TextKey
- type TextLayout
- func (t *TextLayout) Caret(index int) Rect
- func (t *TextLayout) CaretAt(p TextCaretPosition) Rect
- func (t *TextLayout) IndexAt(point Point) int
- func (t *TextLayout) Lines() []TextLine
- func (t *TextLayout) MoveCaret(p TextCaretPosition, direction int) TextCaretPosition
- func (t *TextLayout) NextBoundary(index int) int
- func (t *TextLayout) Objects() []TextObject
- func (t *TextLayout) PositionAt(point Point) TextCaretPosition
- func (t *TextLayout) PreviousBoundary(index int) int
- func (t *TextLayout) SelectionRanges(anchor, caret TextCaretPosition) []TextInputRange
- func (t *TextLayout) SelectionRects(ranges ...TextInputRange) []Rect
- func (t *TextLayout) Size() (float32, float32)
- type TextLine
- type TextLines
- type TextObject
- type TextRange
- type TextShadow
- type TextShape
- type TextSnapshot
- func (s TextSnapshot) ByteLen() int
- func (s TextSnapshot) Len() int
- func (s TextSnapshot) Line(line int) string
- func (s TextSnapshot) LineAt(index int) int
- func (s TextSnapshot) LineCount() int
- func (s TextSnapshot) LineRange(line int) (int, int)
- func (s TextSnapshot) RuneOffset(index int) int
- func (s TextSnapshot) Slice(start, end int) string
- func (s TextSnapshot) String() string
- func (s TextSnapshot) TextForRange(r TextInputRange) (string, TextInputRange)
- func (s TextSnapshot) UTF16Len() int
- func (s TextSnapshot) UTF16Offset(index int) int
- func (s TextSnapshot) Version() uint64
- func (s TextSnapshot) WriteTo(w io.Writer) (int64, error)
- type Theme
- type Timeline
- func (t *Timeline) Arrived() bool
- func (t *Timeline) Duration() time.Duration
- func (t *Timeline) Label(name string, at ...Placement)
- func (t *Timeline) Progress() float32
- func (t *Timeline) Settled() bool
- func (t *Timeline) Time() time.Duration
- func (t *Timeline) Tween(tw Tween, at ...Placement) float32
- type TimelineOptions
- type TitleBar
- type Toast
- type ToastParts
- type Track
- type Transform
- func Perspective(distance float32) Transform
- func Rotation(degrees float32) Transform
- func RotationX(degrees float32) Transform
- func RotationY(degrees float32) Transform
- func Scaling(x, y float32) Transform
- func Skewing(x, y float32) Transform
- func Translation(x, y float32) Transform
- func Translation3D(x, y, z float32) Transform
- func TranslationZ(z float32) Transform
- type Transition
- type TreeItemParts
- type TreeParts
- type Tween
- type UILayer
- func (l *UILayer) Access(name string) (AccessInfo, bool)
- func (l *UILayer) AccessByRole(r Role, name string) (AccessInfo, bool)
- func (l *UILayer) Bitmap() *Bitmap
- func (l *UILayer) Close()
- func (l *UILayer) Cursor() Cursor
- func (l *UILayer) HandleInput(ev InputEvent) bool
- func (l *UILayer) HandleSurfaceInput(m SurfaceMap, ev InputEvent) bool
- func (l *UILayer) Invalidate()
- func (l *UILayer) NeedsFrame() bool
- func (l *UILayer) Render()
- func (l *UILayer) Resize(width, height int)
- func (l *UILayer) Scale() float32
- func (l *UILayer) SetScale(scale float32)
- func (l *UILayer) Size() (w, h int)
- func (l *UILayer) TextCaret() (Rect, bool)
- func (l *UILayer) TextInputActive() (active, noInputMethod bool)
- func (l *UILayer) TextInputClient(m SurfaceMap) TextInputClient
- func (l *UILayer) Version() uint64
- type UV
- type VideoDecoder
- type VideoFrame
- type VideoPlayer
Constants ¶
const ( KeyUnknown = Key(platform.KeyUnknown) KeyEnter = Key(platform.KeyEnter) KeyEscape = Key(platform.KeyEscape) KeyBackspace = Key(platform.KeyBackspace) KeyTab = Key(platform.KeyTab) KeySpace = Key(platform.KeySpace) KeyDelete = Key(platform.KeyDelete) KeyInsert = Key(platform.KeyInsert) KeyHome = Key(platform.KeyHome) KeyEnd = Key(platform.KeyEnd) KeyPageUp = Key(platform.KeyPageUp) KeyPageDown = Key(platform.KeyPageDown) KeyLeft = Key(platform.KeyLeft) KeyRight = Key(platform.KeyRight) KeyUp = Key(platform.KeyUp) KeyDown = Key(platform.KeyDown) KeyF1 = Key(platform.KeyF1) KeyF2 = Key(platform.KeyF2) KeyF3 = Key(platform.KeyF3) KeyF4 = Key(platform.KeyF4) KeyF5 = Key(platform.KeyF5) KeyF6 = Key(platform.KeyF6) KeyF7 = Key(platform.KeyF7) KeyF8 = Key(platform.KeyF8) KeyF9 = Key(platform.KeyF9) KeyF10 = Key(platform.KeyF10) KeyF11 = Key(platform.KeyF11) KeyF12 = Key(platform.KeyF12) KeyMinus = Key(platform.KeyMinus) KeyEqual = Key(platform.KeyEqual) KeyComma = Key(platform.KeyComma) KeyPeriod = Key(platform.KeyPeriod) KeySlash = Key(platform.KeySlash) KeySemicolon = Key(platform.KeySemicolon) KeyQuote = Key(platform.KeyQuote) KeyBracketLeft = Key(platform.KeyBracketLeft) KeyBracketRight = Key(platform.KeyBracketRight) KeyBackslash = Key(platform.KeyBackslash) KeyBackquote = Key(platform.KeyBackquote) KeyContextMenu = Key(platform.KeyContextMenu) Key0 = Key(platform.Key0) Key1 = Key(platform.Key1) Key2 = Key(platform.Key2) Key3 = Key(platform.Key3) Key4 = Key(platform.Key4) Key5 = Key(platform.Key5) Key6 = Key(platform.Key6) Key7 = Key(platform.Key7) Key8 = Key(platform.Key8) Key9 = Key(platform.Key9) KeyA = Key(platform.KeyA) KeyB = Key(platform.KeyB) KeyC = Key(platform.KeyC) KeyD = Key(platform.KeyD) KeyE = Key(platform.KeyE) KeyF = Key(platform.KeyF) KeyG = Key(platform.KeyG) KeyH = Key(platform.KeyH) KeyI = Key(platform.KeyI) KeyJ = Key(platform.KeyJ) KeyK = Key(platform.KeyK) KeyL = Key(platform.KeyL) KeyM = Key(platform.KeyM) KeyN = Key(platform.KeyN) KeyO = Key(platform.KeyO) KeyP = Key(platform.KeyP) KeyQ = Key(platform.KeyQ) KeyR = Key(platform.KeyR) KeyS = Key(platform.KeyS) KeyT = Key(platform.KeyT) KeyU = Key(platform.KeyU) KeyV = Key(platform.KeyV) KeyW = Key(platform.KeyW) KeyX = Key(platform.KeyX) KeyY = Key(platform.KeyY) KeyZ = Key(platform.KeyZ) // KeyBack and KeyForward go back and forward in a history: the side // buttons of a mouse, the keys of keyboards that have them, and on // macOS swipes between pages. A Router takes them. KeyBack = Key(platform.KeyBack) KeyForward = Key(platform.KeyForward) )
Keys.
const ( CodeUnknown = KeyCode(platform.CodeUnknown) CodeKeyA = KeyCode(platform.CodeKeyA) CodeKeyB = KeyCode(platform.CodeKeyB) CodeKeyC = KeyCode(platform.CodeKeyC) CodeKeyD = KeyCode(platform.CodeKeyD) CodeKeyE = KeyCode(platform.CodeKeyE) CodeKeyF = KeyCode(platform.CodeKeyF) CodeKeyG = KeyCode(platform.CodeKeyG) CodeKeyH = KeyCode(platform.CodeKeyH) CodeKeyI = KeyCode(platform.CodeKeyI) CodeKeyJ = KeyCode(platform.CodeKeyJ) CodeKeyK = KeyCode(platform.CodeKeyK) CodeKeyL = KeyCode(platform.CodeKeyL) CodeKeyM = KeyCode(platform.CodeKeyM) CodeKeyN = KeyCode(platform.CodeKeyN) CodeKeyO = KeyCode(platform.CodeKeyO) CodeKeyP = KeyCode(platform.CodeKeyP) CodeKeyQ = KeyCode(platform.CodeKeyQ) CodeKeyR = KeyCode(platform.CodeKeyR) CodeKeyS = KeyCode(platform.CodeKeyS) CodeKeyT = KeyCode(platform.CodeKeyT) CodeKeyU = KeyCode(platform.CodeKeyU) CodeKeyV = KeyCode(platform.CodeKeyV) CodeKeyW = KeyCode(platform.CodeKeyW) CodeKeyX = KeyCode(platform.CodeKeyX) CodeKeyY = KeyCode(platform.CodeKeyY) CodeKeyZ = KeyCode(platform.CodeKeyZ) CodeDigit1 = KeyCode(platform.CodeDigit1) CodeDigit2 = KeyCode(platform.CodeDigit2) CodeDigit3 = KeyCode(platform.CodeDigit3) CodeDigit4 = KeyCode(platform.CodeDigit4) CodeDigit5 = KeyCode(platform.CodeDigit5) CodeDigit6 = KeyCode(platform.CodeDigit6) CodeDigit7 = KeyCode(platform.CodeDigit7) CodeDigit8 = KeyCode(platform.CodeDigit8) CodeDigit9 = KeyCode(platform.CodeDigit9) CodeDigit0 = KeyCode(platform.CodeDigit0) CodeEnter = KeyCode(platform.CodeEnter) CodeEscape = KeyCode(platform.CodeEscape) CodeBackspace = KeyCode(platform.CodeBackspace) CodeTab = KeyCode(platform.CodeTab) CodeSpace = KeyCode(platform.CodeSpace) CodeMinus = KeyCode(platform.CodeMinus) CodeEqual = KeyCode(platform.CodeEqual) CodeBracketLeft = KeyCode(platform.CodeBracketLeft) CodeBracketRight = KeyCode(platform.CodeBracketRight) CodeBackslash = KeyCode(platform.CodeBackslash) CodeSemicolon = KeyCode(platform.CodeSemicolon) CodeQuote = KeyCode(platform.CodeQuote) CodeBackquote = KeyCode(platform.CodeBackquote) CodeComma = KeyCode(platform.CodeComma) CodePeriod = KeyCode(platform.CodePeriod) CodeSlash = KeyCode(platform.CodeSlash) CodeCapsLock = KeyCode(platform.CodeCapsLock) CodeF1 = KeyCode(platform.CodeF1) CodeF2 = KeyCode(platform.CodeF2) CodeF3 = KeyCode(platform.CodeF3) CodeF4 = KeyCode(platform.CodeF4) CodeF5 = KeyCode(platform.CodeF5) CodeF6 = KeyCode(platform.CodeF6) CodeF7 = KeyCode(platform.CodeF7) CodeF8 = KeyCode(platform.CodeF8) CodeF9 = KeyCode(platform.CodeF9) CodeF10 = KeyCode(platform.CodeF10) CodeF11 = KeyCode(platform.CodeF11) CodeF12 = KeyCode(platform.CodeF12) CodePrintScreen = KeyCode(platform.CodePrintScreen) CodeScrollLock = KeyCode(platform.CodeScrollLock) CodePause = KeyCode(platform.CodePause) CodeInsert = KeyCode(platform.CodeInsert) CodeHome = KeyCode(platform.CodeHome) CodePageUp = KeyCode(platform.CodePageUp) CodeDelete = KeyCode(platform.CodeDelete) CodeEnd = KeyCode(platform.CodeEnd) CodePageDown = KeyCode(platform.CodePageDown) CodeArrowRight = KeyCode(platform.CodeArrowRight) CodeArrowLeft = KeyCode(platform.CodeArrowLeft) CodeArrowDown = KeyCode(platform.CodeArrowDown) CodeArrowUp = KeyCode(platform.CodeArrowUp) CodeNumLock = KeyCode(platform.CodeNumLock) CodeNumpadDivide = KeyCode(platform.CodeNumpadDivide) CodeNumpadMultiply = KeyCode(platform.CodeNumpadMultiply) CodeNumpadSubtract = KeyCode(platform.CodeNumpadSubtract) CodeNumpadAdd = KeyCode(platform.CodeNumpadAdd) CodeNumpadEnter = KeyCode(platform.CodeNumpadEnter) CodeNumpad1 = KeyCode(platform.CodeNumpad1) CodeNumpad2 = KeyCode(platform.CodeNumpad2) CodeNumpad3 = KeyCode(platform.CodeNumpad3) CodeNumpad4 = KeyCode(platform.CodeNumpad4) CodeNumpad5 = KeyCode(platform.CodeNumpad5) CodeNumpad6 = KeyCode(platform.CodeNumpad6) CodeNumpad7 = KeyCode(platform.CodeNumpad7) CodeNumpad8 = KeyCode(platform.CodeNumpad8) CodeNumpad9 = KeyCode(platform.CodeNumpad9) CodeNumpad0 = KeyCode(platform.CodeNumpad0) CodeNumpadDecimal = KeyCode(platform.CodeNumpadDecimal) CodeIntlBackslash = KeyCode(platform.CodeIntlBackslash) CodeContextMenu = KeyCode(platform.CodeContextMenu) CodePower = KeyCode(platform.CodePower) CodeNumpadEqual = KeyCode(platform.CodeNumpadEqual) CodeF13 = KeyCode(platform.CodeF13) CodeF14 = KeyCode(platform.CodeF14) CodeF15 = KeyCode(platform.CodeF15) CodeF16 = KeyCode(platform.CodeF16) CodeF17 = KeyCode(platform.CodeF17) CodeF18 = KeyCode(platform.CodeF18) CodeF19 = KeyCode(platform.CodeF19) CodeF20 = KeyCode(platform.CodeF20) CodeF21 = KeyCode(platform.CodeF21) CodeF22 = KeyCode(platform.CodeF22) CodeF23 = KeyCode(platform.CodeF23) CodeF24 = KeyCode(platform.CodeF24) CodeAudioVolumeMute = KeyCode(platform.CodeAudioVolumeMute) CodeAudioVolumeUp = KeyCode(platform.CodeAudioVolumeUp) CodeAudioVolumeDown = KeyCode(platform.CodeAudioVolumeDown) CodeNumpadComma = KeyCode(platform.CodeNumpadComma) CodeIntlRo = KeyCode(platform.CodeIntlRo) CodeKanaMode = KeyCode(platform.CodeKanaMode) CodeIntlYen = KeyCode(platform.CodeIntlYen) CodeConvert = KeyCode(platform.CodeConvert) CodeNonConvert = KeyCode(platform.CodeNonConvert) CodeLang1 = KeyCode(platform.CodeLang1) CodeLang2 = KeyCode(platform.CodeLang2) CodeLang3 = KeyCode(platform.CodeLang3) CodeLang4 = KeyCode(platform.CodeLang4) CodeControlLeft = KeyCode(platform.CodeControlLeft) CodeShiftLeft = KeyCode(platform.CodeShiftLeft) CodeAltLeft = KeyCode(platform.CodeAltLeft) CodeSuperLeft = KeyCode(platform.CodeSuperLeft) CodeControlRight = KeyCode(platform.CodeControlRight) CodeShiftRight = KeyCode(platform.CodeShiftRight) CodeAltRight = KeyCode(platform.CodeAltRight) CodeSuperRight = KeyCode(platform.CodeSuperRight) )
Keys by position.
const ( Shift = Modifiers(platform.ModShift) Ctrl = Modifiers(platform.ModCtrl) Alt = Modifiers(platform.ModAlt) // Super is Command on macOS and the Windows key elsewhere. Super = Modifiers(platform.ModSuper) )
Modifier keys.
const ( // PointerMouse is a mouse, or a touchpad, which moves the pointer as // one does. PointerMouse = PointerType(platform.PointerMouse) // PointerPen is a pen on a tablet or a screen, its eraser too. PointerPen = PointerType(platform.PointerPen) // PointerTouch is a finger on a touchscreen. PointerTouch = PointerType(platform.PointerTouch) )
Pointer devices.
const ( CursorDefault = Cursor(platform.CursorDefault) CursorPointer = Cursor(platform.CursorPointer) CursorText = Cursor(platform.CursorText) CursorMove = Cursor(platform.CursorMove) CursorResizeEW = Cursor(platform.CursorResizeEW) CursorResizeNS = Cursor(platform.CursorResizeNS) CursorResizeNWSE = Cursor(platform.CursorResizeNWSE) CursorResizeNESW = Cursor(platform.CursorResizeNESW) CursorNotAllowed = Cursor(platform.CursorNotAllowed) CursorCrosshair = Cursor(platform.CursorCrosshair) CursorGrab = Cursor(platform.CursorGrab) CursorGrabbing = Cursor(platform.CursorGrabbing) // CursorResizeN, E, S and W resize toward one side only, as at the // limit of a resize. CursorResizeN = Cursor(platform.CursorResizeN) CursorResizeE = Cursor(platform.CursorResizeE) CursorResizeS = Cursor(platform.CursorResizeS) CursorResizeW = Cursor(platform.CursorResizeW) // CursorResizeColumn and CursorResizeRow move the line between columns // or rows, as of a table or a split. CursorResizeColumn = Cursor(platform.CursorResizeColumn) CursorResizeRow = Cursor(platform.CursorResizeRow) CursorVerticalText = Cursor(platform.CursorVerticalText) // CursorCopy and CursorAlias show that a drop copies or links what is // dragged. CursorCopy = Cursor(platform.CursorCopy) CursorAlias = Cursor(platform.CursorAlias) CursorContextMenu = Cursor(platform.CursorContextMenu) // CursorNone hides the pointer over the element, as over a video. CursorNone = Cursor(platform.CursorNone) // CursorProgress shows that the app is busy while it can still be // used, as over an element marked busy (aria-busy), and CursorWait // that it cannot be. CursorProgress = Cursor(platform.CursorProgress) CursorWait = Cursor(platform.CursorWait) CursorHelp = Cursor(platform.CursorHelp) // CursorCell selects cells, as of a spreadsheet. CursorCell = Cursor(platform.CursorCell) // CursorZoomIn and CursorZoomOut show that a click zooms, as over an // image. CursorZoomIn = Cursor(platform.CursorZoomIn) CursorZoomOut = Cursor(platform.CursorZoomOut) // CursorAllScroll scrolls in every direction, as a middle-button // autoscroll does. CursorAllScroll = Cursor(platform.CursorAllScroll) // CursorNoDrop shows that what is dragged cannot be dropped here. CursorNoDrop = Cursor(platform.CursorNoDrop) )
Pointer shapes.
const ( TextDownstream = text.Downstream TextUpstream = text.Upstream )
const AlertDismissed = -2
AlertDismissed is what AlertDialog returns in the frame Escape closes the alert, choosing no button.
const RepeatForever = -1
RepeatForever repeats a sequence of Keyframes, or a Timeline, for as long as the view builds it (KeyframeOptions.Repeat, TimelineOptions.Repeat).
Variables ¶
var ( Smooth = Animation{Spring: SpringOptions{Duration: defaultSpringDuration}} Snappy = Animation{Spring: SpringOptions{Duration: defaultSpringDuration, Bounce: 0.15}} Bouncy = Animation{Spring: SpringOptions{Duration: defaultSpringDuration, Bounce: 0.3}} )
Springs that settle without bouncing, with a little bounce, and with a visible one, as SwiftUI's of the same names; Smooth is the zero Animation's.
var Auto = float32(math.Inf(1))
Auto is an automatic margin, which takes the free space on its side, as in CSS: Margin(0, Auto) centers an element horizontally, and a Row's child with Margin(0, 0, 0, Auto) goes to the end with those after it.
var Cmd = func() Modifiers { if runtime.GOOS == "darwin" { return Super } return Ctrl }()
Cmd is the modifier of the platform's shortcuts: Command on macOS, Control elsewhere, as in Cmd+C.
var Transparent = Color{}
Transparent is the color of nothing.
Functions ¶
func AlertDialog ¶
AlertDialog shows an alert over the window while *open is true, as AppKit's: title, message, and buttons, the last of which is the default, in the accent color, with the focus, which Enter clicks. Escape closes the alert choosing no button, as canceling does, whatever the buttons say; a click outside the alert does nothing. It returns the index of the button clicked, in the frame it is, which closes the alert, AlertDismissed in the frame Escape closes it, and -1 otherwise. An alert that must be answered stays open by setting *open back to true on AlertDismissed. Assistive technology sees an alert named by title and described by message.
switch ui.AlertDialog(c, &app.asking, "Delete “Notes”?", "You can't undo this.", "Cancel", "Delete") {
case 1:
app.delete()
}
func DataDragOver ¶
DataDragOver makes e a native destination, as DropData does, and returns the advertised formats and operations while a matching drag is over it. Hover never invokes a data provider.
func DragOver ¶
DragOver makes e take values of type T dragged within the window, as Drop does, and returns the value dragged over it, for showing it would take it.
func Drop ¶
Drop makes e take values of type T dragged within the window (Element.Drag) and returns the value dropped on it since the last frame.
if f, ok := ui.Drop[*File](folder); ok {
app.move(f, dir)
}
func DropData ¶
DropData makes e take native transfers matching options, and reports a completed drop once, in the next frame. Decode custom formats explicitly from the returned Data. Empty Formats accepts nothing.
func FocusedValue ¶
func FocusedValue[T comparable](c *Context, field *T) T
FocusedValue returns actual focus from the committed window, independently of construction order or a pending FocusBind request. Zero means no member has focus. Use only on the UI thread.
func ImageSize ¶
func ImageSize(src ImageSource) (w, h float32)
ImageSize returns the size Image shows src at by default, in DIPs: a bitmap's pixels, or the size an SVG says it has. It is 0×0 for nil.
func Local ¶
Local returns state of type T that element e keeps from frame to frame, keyed by key among its states; init creates it the first time. Custom widgets keep what they need with it, on the element they create.
The element owns what init made. When a frame no longer builds it, a value that is an io.Closer (T or *T has Close() error) is closed once, on the main thread, after that frame, as the web aborts an AbortController as an element is removed: a component cancels in Close the work it started, as a streaming request, a ticker or a subscription:
s := ui.Local(e, "stream", func() *stream { return startStream(url) })
An element leaving with an exit transition closes them once its exit ended, and every element as its window closes. A nil value is not closed, and Close's error is ignored. Keep a value the element must not close, as one the app shares, in the app's state.
func Nearest ¶
Nearest returns a Snap (DraggableOptions) that chooses the nearest of points, as the heights a sheet rests at:
Snap: ui.Nearest(ui.Point{}, ui.Point{Y: 200}, ui.Point{Y: 400}),
func Overlay ¶
func Overlay(c *Context, fn func())
Overlay builds fn's elements above the rest of the window. Place them with Absolute, Left and Top, in DIPs relative to the window, or beside another element with AttachTo. Each, as it goes with the focus in it, gives the focus back to the element that had it as it came. Built inside the children of a Themed, they take its theme.
func Project ¶
Project returns where a value going at velocity, in its units per second, comes to rest as iOS's scroll views slow down (their normal deceleration rate): where a fling would carry it, to choose the target a spring takes it to (SpringOptions.Velocity).
func RegisterFont ¶
RegisterFont adds a TrueType or OpenType font, or collection, that text can use with Font(family). An empty family keeps the font's own name. The fonts registered under a family make it up, apart from other fonts of their own family.
func Render ¶
Render draws a frame of view in a window of width×height DIPs at scale device pixels per DIP, without a window: for snapshots and tests.
func Rubberband ¶
Rubberband returns value held within lo and hi as iOS holds content dragged past its edges: beyond them, it goes less and less far, as on a rubber band, the less the larger dimension is (the size of what is dragged, along the drag).
func SafeToOpen ¶
SafeToOpen reports whether a link to url can open in the system when others wrote it, as a message, a language model's reply or a pasted document: an http, https or mailto address. Other schemes and paths open files and run programs (on Windows, "calc" and \\host\x.exe run), and javascript: runs script in a browser. Markdown views and the rich text editor open only these, unless the app opens links itself.
func UTF16ByteOffset ¶
UTF16ByteOffset converts a native offset to a UTF-8 byte offset, rounding inside a surrogate pair down to the rune's beginning and clamping to s.
Types ¶
type AccessInfo ¶
type AccessInfo struct {
// Role is the element's role, as Role set it or as its widget or what
// it does gave it: never RoleAuto or RoleNone.
Role Role
// Name is the accessible name: the Label, or the text inside the
// element. Value is its value, as a text field's text, the choice a
// pop-up button shows, or what a slider reads (aria-valuetext).
// Description is read after the name, as a tooltip or a field's
// error, and Placeholder is what an empty text field shows.
Name, Value, Description, Placeholder string
// RoleDescription is what the app calls the role in its place
// (aria-roledescription), as a "carousel" group; "" for the
// platform's name of Role.
RoleDescription string
// Bounds is the element's visible box, in the window's DIPs as Find's.
Bounds Rect
// Checked is set on a check box, switch, radio button or menu item
// that is on, and on a toggle button pressed (aria-checked,
// aria-pressed); Mixed in its place on one partly on.
Checked, Mixed bool
// Expanded is set while what the element opens shows; Expandable on
// an item of a tree with children.
Expanded, Expandable bool
// Selected is set on the tab chosen, on the items of a tree and the
// rows of a list, a table or a grid chosen, and on the cells of a
// table or a grid chosen with Checked (aria-selected), which are
// Selectable where their list, table or grid chooses them;
// Multiselectable is set on a list, a table or a grid choosing
// several.
Selected, Selectable, Multiselectable bool
// Busy is set while the element's content is about to change
// (aria-busy).
Busy bool
// Disabled is set on an element that takes no input, Invalid on one
// whose value is not valid, as a field with an error.
Disabled, Invalid bool
// Focusable is set on an element that takes the keyboard focus, and
// Focused on the one assistive technology has the focus on: the
// element with it, or the option the arrows are on in a list or a
// combobox that keeps it (ActiveDescendant).
Focusable, Focused bool
// ReadOnly, Multiline, Password and Search tell of a text field.
ReadOnly, Multiline, Password, Search bool
// Sort is the order a table's rows are sorted in by the column whose
// header the element is (aria-sort), SortNone for others.
Sort SortDirection
// HasPopup is the kind of popup the element opens (aria-haspopup),
// PopupNone for none.
HasPopup Popup
// Controls are the accessible names of the elements the element
// controls (aria-controls), in the last frame, in the order Controls
// gave them: Access finds each.
Controls []string
// DescribedBy are the accessible names of the elements describing the
// element (aria-describedby), whose text Description holds, and
// ErrorMessage those of the elements holding its error
// (aria-errormessage), given while it is Invalid, in the order
// DescribedBy and ErrorMessage gave them.
DescribedBy, ErrorMessage []string
// Vertical is set on a slider going up, a separator running up and
// down, and an element told it is vertical (aria-orientation);
// Horizontal on one told it runs across (Orientation). Segment is set
// on a segment of a segmented control or a group of toggles.
Vertical, Horizontal, Segment bool
// Offscreen is set on an element built out of view, as the rows a
// list builds beyond its edges.
Offscreen bool
// Current is the item the element is the current one of
// (aria-current), CurrentNone for none.
Current Current
// AutoComplete is what the suggestions of a text field or a combo
// box complete as the user types (aria-autocomplete),
// AutoCompleteNone for none.
AutoComplete AutoComplete
// KeyShortcuts are the keys that press or focus the element
// (aria-keyshortcuts), as the platform's menus write them and
// separated by spaces: "⌘K" for Cmd+K on macOS, "Ctrl+K" elsewhere.
KeyShortcuts string
// Level is the rank of a heading, or how deep an item of a tree is,
// from 1; 0 for other elements.
Level int
// PosInSet is the place of an item in its set, from 1, and SetSize
// the size of the set, as a list's rows and the list have them; 0
// when not given.
PosInSet, SetSize int
// RowCount and ColumnCount are how many rows and columns a table or
// a grid has (aria-rowcount, aria-colcount), and RowIndex and
// ColumnIndex the place of a row or a cell among them, from 1
// (aria-rowindex, aria-colindex), as the app gave them; 0 when not
// given.
RowCount, ColumnCount, RowIndex, ColumnIndex int
// RowSpan and ColumnSpan are how many rows and columns a cell covers
// (aria-rowspan, aria-colspan), as its RowSpan and ColumnSpan set
// them; 0 for one.
RowSpan, ColumnSpan int
// Min, Max and Now are the range and the value of a slider, progress
// bar, meter or stepper (aria-valuemin, -valuemax and -valuenow), Now
// below Min for progress of unknown length; Step is how far the keys
// move the value, 0 for none.
Min, Max, Now, Step float64
}
AccessInfo is what assistive technology sees of an element of the last frame (Tester.Access): its role, name, value and states, as the accessibility tree gives them to screen readers.
type AccordionParts ¶
type AccordionParts struct {
Root Element
// contains filtered or unexported fields
}
AccordionParts contains checked handles for the parts of a custom widget.
func AccordionBase ¶
func AccordionBase(c *Context) AccordionParts
AccordionBase creates an accordion without a look: a column of sections, each a CollapsibleBase that Item makes, opening and closing on its own, whose headers Up and Down move the keyboard focus between, as do Home and End. Build the sections in Root:
acc := ui.AccordionBase(c)
acc.Root.Gap(4).Children(func() {
for i := range app.sections {
s := &app.sections[i]
item := acc.Item(&s.open)
item.Trigger.Padding(8, 12).Radius(6).Children(func() {
ui.Text(c, s.title).Grow(1)
ui.Icon(c, chevron).Rotate(180 * item.Progress())
})
item.Panel(func() { s.build(c) })
}
})
Accordion is AccordionBase with the theme's look.
func (AccordionParts) Item ¶
func (_handle AccordionParts) Item(open *bool) CollapsibleParts
Item creates a section of the accordion, open while *open: a CollapsibleBase, whose Trigger is its header, which a click opens and closes, as do Enter and Space, and the arrows, Home and End leave for the other sections' headers; Panel builds what shows below it while it is open. Assistive technology sees the header as a disclosure, expanded while open.
type Align ¶
type Align uint8
Align positions children along an axis: Justify places them along the main axis (the direction of a Row or Column), AlignItems and AlignSelf across it.
const ( // Start is the left of a row, the top of a column. Start Align = iota Center End // Stretch makes children as large as the container across its axis. Stretch // SpaceBetween, SpaceAround and SpaceEvenly spread children along the // main axis (Justify), or lines and grid tracks (AlignContent). SpaceBetween SpaceAround SpaceEvenly // Baseline lines up the first lines of text of the children of a row, // or of a grid's row, as a large price beside its small unit does // (AlignItems and AlignSelf). A child without text lines up its // bottom. Across a column it is Start. Baseline )
type Anchor ¶
type Anchor uint8
Anchor is a point of a box: a corner, the middle of a side, or the center.
const ( AnchorTopLeft Anchor = iota AnchorTop AnchorTopRight AnchorLeft AnchorCenter AnchorRight AnchorBottomLeft AnchorBottom AnchorBottomRight AnchorTopStart AnchorStart AnchorBottomStart AnchorTopEnd AnchorEnd AnchorBottomEnd )
Anchors, from left to right and top to bottom, then those on the side lines start and on the other: on the left and the right, or the right and the left of an element laid out right to left (Direction), as Flutter's AlignmentDirectional.
type Animation ¶
type Animation struct {
// Duration and Ease make a curve: Ease, EaseOut when nil, over
// Duration.
Duration time.Duration
Ease Easing
// Spring is the spring of an Animation without a Duration.
Spring SpringOptions
// Delay is how long the value keeps going as it was after its target
// changes, before it heads for the new one, as a list's rows do one
// after another with Delay: time.Duration(i) * 30 * time.Millisecond.
Delay time.Duration
// Oklab mixes the colors it moves (AnimateColor, and a Transition's
// colors, those of an element of its Match and a ContentTransition's
// text morphing) in the Oklab color space, as a gradient's Oklab
// does, instead of in sRGB: between two saturated colors, the way
// keeps their lightness and saturation rather than going through a
// dull, darker middle.
Oklab bool
// NonMotion says that the value AnimateTo animates moves nothing on
// screen, as an opacity, a blur or a crossfade: it still animates
// while the desktop asks for less motion (Preferences.ReduceMotion),
// as colors and a Transition's fades do, where other values go to
// their targets at once. Leave it off for a position, a size, a
// scale or a scroll. What MyGo moves itself (ScrollTo, a pose, a
// Transition) knows what moves, and does not read it.
NonMotion bool
}
Animation says how a value goes to a new target: along an easing curve for Duration, or, when Duration is zero, with a spring, which keeps the value's velocity when the target changes again on the way. The zero Animation is Smooth's spring:
x := card.AnimateTo("x", target, ui.Snappy)
fade := card.AnimateTo("fade", target, ui.Animation{Duration: 150 * time.Millisecond, Ease: ui.EaseInOut})
type AutoComplete ¶
type AutoComplete uint8
AutoComplete is what the suggestions of a text input complete as the user types (Element.AutoComplete), as ARIA's aria-autocomplete says.
const ( // AutoCompleteNone suggests nothing as the user types: the popup of // a combobox, if any, shows the same options whatever is typed. AutoCompleteNone AutoComplete = iota // AutoCompleteInline completes the text in place: the rest of the // value the input guesses is inserted after the caret, selected. AutoCompleteInline // AutoCompleteList shows a popup of the values that complete what // was typed, as the options of a Combobox or an Autocomplete. AutoCompleteList // AutoCompleteBoth shows the popup, and completes the text in place // with the option the arrows are on. AutoCompleteBoth )
type Bitmap ¶
type Bitmap struct {
// contains filtered or unexported fields
}
Bitmap is an image to show with Image. Create it once: converting an image is not free.
func DecodeBitmap ¶
DecodeBitmap decodes a PNG, JPEG, GIF (its first frame), WebP or BMP image. A JPEG photo shows upright, as its camera's EXIF orientation says. The bitmap keeps data, without a copy, to decode it again after ReleasePixels.
func NewBitmap ¶
NewBitmap converts img. The bitmap keeps no reference to img, unless ReleasePixels has it convert img again when it needs the pixels.
func (*Bitmap) Pixelated ¶
Pixelated draws the bitmap's pixels as squares of their colors where it shows larger than its size, as pixel art draws, instead of blending neighbors smoothly. At whole multiples of its size, each pixel is a square of whole pixels of the screen; at others, squares of even sizes whose edges blend across one pixel of the screen, so that none is wider than the next and they glide when they move, as Ebitengine's FilterPixelated. Where it shows smaller, it is as smooth as any. It returns the bitmap.
func (*Bitmap) ReleasePixels ¶
func (b *Bitmap) ReleasePixels()
ReleasePixels drops the CPU pixels of a bitmap, those of its picture and of its levels, keeping the copies a GPU renderer uploaded: the bitmap draws as before. The pixels are made again when something needs them — a renderer that lost its textures or let one go, the CPU renderer, or a level for drawing the bitmap smaller — and a GPU renderer's upload drops them again: decoded again from the data DecodeBitmap took, or converted again from the image NewBitmap took, which the bitmap keeps from then on, without a copy. Either must stay as it was. A bitmap NewBitmap made of an image the app no longer keeps (or of a type other than package image's), a canvas's, or one Update changed has nothing else to make them from and keeps them. Call it once the bitmap has shown, on the main thread, as drawing does.
func (*Bitmap) Update ¶
Update shows img in place of the bitmap's picture, for one that changes as video does: the GPU keeps the bitmap's texture and uploads the new pixels, where a new Bitmap a frame would make a texture each, and keep each for a while. An *image.RGBA of rows 4×width bytes long from the origin, as image.NewRGBA makes, is taken as it is, without a copy: don't change its pixels until the next Update. Call it on the main thread, in the view or through Window.Update, which redraws the window to show it.
type BorderStyle ¶
type BorderStyle uint8
BorderStyle is how a border draws.
const ( BorderSolid BorderStyle = iota // BorderDashed draws each side in dashes about three times as long as // the side is wide, with a dash at both ends. BorderDashed )
type Canvas ¶
type Canvas struct {
// contains filtered or unexported fields
}
A Canvas is a bitmap that a painter draws, on the GPU where the window draws there: render to texture, as SkSurface, LÖVE's Canvas and raylib's RenderTexture2D. A view draws what seldom changes into one once, as a chart's grid or a map's ground, and shows it every frame for the price of an image; fades or tints a whole layer at once; or draws at a resolution of its own and shows it scaled, as pixel art scales up crisp (game.IntegerFit, in the game plugin).
It keeps what was last drawn into it until Draw draws it anew, and shows anywhere a bitmap does, through Bitmap.
func (*Canvas) Bitmap ¶
Bitmap returns the bitmap the canvas shows as, for Image, Painter.Image and Painter.ImageRegion; make it Pixelated to scale pixel art up crisp.
func (*Canvas) Draw ¶
Draw draws the canvas anew, cleared to transparent, with what fn paints with cp in the canvas's pixels, during the frame p paints: a Draw callback's painter. What fn paints is what any painter paints: shapes, paths, text, images, parts of them, other canvases, under transforms and clips. Drawn, the canvas shows it from this frame on.
type CellsStyle ¶
type CellsStyle struct {
// Cell is the background of the cells of the block, and the border of
// the cursor where it is out of the block.
Cell Color
// CellText is the color of their text and of the cursor's border in
// the block, as AccentText is of chosen rows.
CellText Color
// Row is the background of the rows chosen.
Row Color
// Stripe is the background of every other row.
Stripe Color
}
A CellsStyle paints the block of cells a Table chooses (CellSelect), and the rows chosen, in its own colors rather than the accent, as a spreadsheet does: the chosen cell stands out over its row, and the rows alternate.
grid.CellsStyle = ui.CellsStyle{
Cell: t.Accent,
CellText: t.AccentText,
Row: t.Accent.Alpha(0.12),
Stripe: t.Text.Alpha(0.04),
}
A zero color paints none, leaving the theme's background, except where Cell is zero: the block then shows as chosen rows do, in the accent.
type CheckState ¶
type CheckState uint8
CheckState is what a check box that can be mixed shows (CheckboxStateBase): unchecked, checked, or mixed, as one checking a group whose boxes differ.
const ( CheckOff CheckState = iota CheckOn CheckMixed )
type CollapsibleParts ¶
type CollapsibleParts struct {
Trigger Element
// contains filtered or unexported fields
}
CollapsibleParts contains checked handles for the parts of a custom widget.
func CollapsibleBase ¶
func CollapsibleBase(c *Context, open *bool) CollapsibleParts
CollapsibleBase creates a collapsible without a look, open while *open: its Trigger, and below it the panel Panel builds. Collapsible is CollapsibleBase with the theme's look.
func (CollapsibleParts) Panel ¶
func (_handle CollapsibleParts) Panel(fn func()) Element
Panel builds fn in the panel of the collapsible while it is open, and as it opens and closes, when the panel grows and shrinks with Progress, clipping what fn built. It returns the column holding what fn builds, to style, and nil while the collapsible is closed.
func (CollapsibleParts) Progress ¶
func (_handle CollapsibleParts) Progress() float32
Progress returns how far the collapsible is open, from 0 closed to 1 open, moving between them as it opens and closes: draw its arrow from it. It moves at once where the desktop asks for less motion.
type Color ¶
type Color struct {
R, G, B, A uint8
// contains filtered or unexported fields
}
Color is a color with straight (not premultiplied) alpha. R, G, B and A are its sRGB value. A Color from Oklch may lie outside the sRGB gamut and then also holds the wide color, which a window that draws a wide gamut (on a Mac whose screen shows one) shows in place of R, G and B; every other one shows them, the nearest sRGB color, found as CSS Color 4 does. Set R, G or B of such a color and the wide color is stale: make a new one instead.
func Hex ¶
Hex parses "#rgb", "#rgba", "#rrggbb" or "#rrggbbaa". It panics on other input, which is a mistake in the program.
func Oklch ¶
Oklch returns the color of CSS's oklch(l c h): lightness l from 0 to 1, chroma c (about 0 to 0.4) and hue h in degrees. Use Alpha for oklch(l c h / a).
A color Display P3 cannot show loses chroma, keeping its lightness and hue, as CSS does; a negative chroma is 0. A color outside the sRGB gamut is shown as it is by a window that draws a wide gamut, and as the nearest sRGB color by every other (see Color).
func (Color) MixOklab ¶
MixOklab returns the color t of the way from c to o, mixed in the Oklab color space, as a gradient's Oklab mixes and CSS's color-mix(in oklab) does: between two saturated colors, the mix keeps their lightness and saturation, where Mix's, in sRGB, is duller and darker. A mix outside the sRGB gamut holds its wide color, as a color from Oklch does. As in CSS, the colors mix with premultiplied alpha: a color mixed with Transparent keeps its hue and fades, rather than darkening.
type ColumnRange ¶
type ColumnRange struct {
// Cursor is the column the keys move from, where the border shows.
Cursor string
// Anchor is the column Shift extends the columns from.
Anchor string
// All chooses every column, as a click on a RowHeader cell does.
All bool
}
ColumnRange is the columns of the block of cells a Table chooses (ListState.CellSelect), by column ID (TableColumn.ID, or Title).
type ComboboxParts ¶
type ComboboxParts struct {
Input Element
// contains filtered or unexported fields
}
ComboboxParts contains checked handles for the parts of a custom widget.
func ComboboxBase ¶
func ComboboxBase(c *Context, text *string) ComboboxParts
ComboboxBase creates a combobox without a look: a text input editing *text, whose popup of options, built with Popup and Item, opens below it as the user types, clicks it or presses Down. Up and Down move among the options, Enter or a click chooses one, which Chosen reports, and Escape, or the input losing the focus, closes the popup. Assistive technology sees a combo box, and follows the option the arrows are on; tell it with AutoComplete when the options are those matching what was typed (AutoCompleteList).
cb := ui.ComboboxBase(c, &app.query)
cb.Input.Padding(6, 10).Border(1, gray).Label("Font")
cb.Popup(func(panel ui.Element) {
panel.Padding(4).Background(white).Border(1, gray)
for _, f := range fonts {
item := cb.Item(f).Padding(6, 10)
if item.Highlighted() {
item.Background(blue).TextColor(white)
}
item.Children(func() { ui.Text(c, f) })
}
})
if f, ok := cb.Chosen(); ok {
app.font = f
}
Combobox, Autocomplete and TokenField are built on it.
func (ComboboxParts) Chosen ¶
func (_handle ComboboxParts) Chosen() (string, bool)
Chosen returns the option the user chose in this frame, by a click or Enter: ask it after Popup, which takes the input of the options it built as it returns, so the choice can be handled in the same build pass.
func (ComboboxParts) Filtering ¶
func (_handle ComboboxParts) Filtering() bool
Filtering reports whether the text is what the user typed since the popup opened, which the options should match; it is not when the popup opened by a click or Down, which shows them all.
func (ComboboxParts) Item ¶
func (_handle ComboboxParts) Item(value string) Element
Item creates an option: a row that is Highlighted when the pointer or the arrows are on it, and that chooses value when clicked. The option the highlight moves to scrolls into view, once, so that the wheel scrolls on past it.
func (ComboboxParts) Open ¶
func (_handle ComboboxParts) Open() bool
Open reports whether the popup shows.
func (ComboboxParts) Popup ¶
func (_handle ComboboxParts) Popup(fn func(panel Element)) Element
Popup shows the popup below the input, at least as wide, while it is open: fn styles the panel and builds the options with Item. A popup without options shows only while it holds something else to read, as a row saying that nothing matches, which assistive technology reads out as it appears:
if len(matches) == 0 {
ui.Text(c, "No matches found").Padding(6, 10)
}
It returns the panel, or nil while it does not show.
func (ComboboxParts) SetOpen ¶
func (_handle ComboboxParts) SetOpen(o bool)
SetOpen opens or closes the popup.
type ConicGradient ¶
type ConicGradient struct {
Stops []GradientStop
// Center is the point the colors turn around, in fractions of the
// box's width and height from its top left corner; the zero Point is
// its middle.
Center Point
// Angle is where the turn starts, in degrees clockwise from upwards, as
// CSS's "from": 90 starts at the right, where SwiftUI's and Flutter's
// start.
Angle float32
// Oklab mixes the colors in the Oklab color space, as LinearGradient's
// does.
Oklab bool
}
ConicGradient blends colors around a point, as CSS's conic-gradient() does (SwiftUI's AngularGradient, Flutter's SweepGradient): its stops at their places around a turn, clockwise from its angle.
e.ConicGradient(ui.ConicGradient{Stops: []ui.GradientStop{{red, 0}, {blue, 0.5}, {red, 1}}})
type Content ¶
type Content struct {
// contains filtered or unexported fields
}
Content is a user interface for a window, the value of mygo.WindowOptions.Content. Create it with View.
func View ¶
View returns the content of a window whose user interface view builds, for mygo.WindowOptions.Content:
mygo.NewWindow(mygo.WindowOptions{Title: "Counter", Content: ui.View(app.View)})
view runs on the main thread whenever the window needs a frame: after input, after Context.Invalidate or Window.Invalidate, and while something animates. A Content can serve several windows, each with its own state.
func (*Content) AttachContent ¶
AttachContent connects the content to a window; package mygo calls it.
type ContentTransition ¶
type ContentTransition struct {
Numeric, Down, Morph bool
// Animation is how the content changes: a spring arriving in about
// 350 ms without bouncing when nil.
Animation *Animation
}
ContentTransition is how an element's content changes (Element ContentTransition): its text, its icon, or its picture.
By default, the old content fades out as the new fades in; an icon shrinks away as the new grows in, as SwiftUI's replace symbol effect. Numeric rolls the characters of a line of text that change, as a counter's digits, those that stay staying: the new come up from below, or, Down, from above, as SwiftUI's numericText.
Morph moves the characters the old and the new text have in common from where they were to where they are, growing or shrinking to their size, those of the old text alone fading out and those of the new fading in, as Keynote's Magic Move by characters: words reflowing, a title rewritten, letters rearranged. Rich text morphs too: its characters go to the colors of their spans, and its lines and highlights fade. A text flying with a Transition's Match (Fly) morphs from the text of the element of its Match.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is the window's stable UI context. Use it on the UI thread while building a view. Children share it and temporarily change its parent. Publish background results with Window.Update or Services.Invalidate.
func (*Context) AddToast ¶
AddToast shows t near the bottom of the window, as Toast does, and returns its ID, to close it with CloseToast:
id := c.AddToast(ui.Toast{Title: "Uploading", Timeout: -1})
// ...
c.CloseToast(id)
Adding a toast with the ID of one showing changes that toast, which shows anew. Toasts show with the theme's look, unless the view builds them with ToastViewportBase.
func (*Context) After ¶
After asks for another frame after d, for something that changes with time, such as a clock.
func (*Context) AnimationFrame ¶
func (_handle *Context) AnimationFrame()
AnimationFrame asks for another frame as soon as the display can show it, for something moving. Call it in every frame while it moves. A drawing that moves while the layout stays asks with Painter.AnimationFrame instead, whose frames do not build the view.
func (*Context) Announce ¶
Announce asks screen readers to read text out once, after what they are reading, for news the keyboard focus does not bring, as a search done or a file saved: a Router announces the title of a page it shows, and a toast its text. It does nothing while no assistive technology reads the window.
func (*Context) CloseToast ¶
CloseToast closes the toast with id, or every toast when id is empty, and runs their OnClose.
func (*Context) Direction ¶
Direction returns the direction of the elements built now: that of the element they go in. Widgets of an app's own read it to draw what points along the line, as an arrow forward:
forward := "M5 2 11 8 5 14"
if c.Direction() == ui.RightToLeft {
forward = "M11 2 5 8 11 14"
}
func (*Context) DisableAnimations ¶
func (_handle *Context) DisableAnimations()
DisableAnimations makes the values that animate in this frame (AnimateTo, Animate, Spring), the element transitions and the pages of routers go to their targets at once, as SwiftUI's disablesAnimations: for a change that should not show as motion, as restoring a window's state or jumping to a search result. Call it before building what changes. Keyframes and timelines, which play on their own rather than towards a target, go on as they were: Seek a Timeline to jump it.
func (*Context) FocusTakesText ¶
FocusTakesText reports whether the element with the keyboard focus takes text, typed or composed: a text input or text area, or an editor of rich text or code, that is not read only, or an element that takes text itself (HandleTextInput, TextCaret). It is the web's guard of single-key shortcuts (isContentEditable, an input or a textarea, the role textbox): a command palette's letters step aside while a field takes them as text.
if !c.FocusTakesText() && c.Shortcut(0, ui.KeyK) {
app.palette = true
}
It is false while the window does not have the keyboard, as the window tells the system's input methods then.
func (*Context) FocusWithin ¶
func (*Context) Instant ¶
Instant reports whether this frame shows animated values at once (DisableAnimations). Views read it to render a change settled in the same frames where its animations are disabled.
func (*Context) Invalidate ¶
func (c *Context) Invalidate()
Invalidate requests a frame from any goroutine.
func (*Context) Key ¶
Key assigns the identity of the next control before its state is read. A compound widget consumes the key for its outermost element.
func (*Context) KeyDown ¶
KeyDown reports whether key is held down in the window, whichever element has the focus and whether or not one took the key, without taking it from them: a cheat sheet of shortcuts lights the keys held while its search field has the focus. A frame that reads it is drawn again as the keys held change. Keys count as shortcuts take them (a chord of a key the layout types no US key for, as S on a Cyrillic layout, by its position); the modifier keys are Modifiers'. A key whose press ran a menu item's shortcut went to the menu, not the window. The window lets go of every key as it loses the keyboard, whose releases go elsewhere.
func (*Context) KeysDown ¶
KeysDown returns the keys held down in the window, as KeyDown tells them, in the order they were pressed; nil while none is. A cheat sheet fades the rows of shortcuts that use none of them:
held := c.KeysDown()
for _, s := range app.shortcuts {
row := shortcutRow(c, s)
if len(held) > 0 && !s.usesAny(held) {
row.Opacity(0.4)
}
}
func (*Context) Locale ¶
Locale returns the language the app shows (mygo.App.Locale), a BCP 47 tag such as "en" or "zh-Hans", for what the view says in it. Text is in it unless an element says otherwise (Element.Lang). A frame follows its changes, as App.SetLocale makes them.
func (*Context) MeasureText ¶
MeasureText returns the size spans of text take as Painter.RichText draws them, wrapping lines at width DIPs (none for 0), to lay out what depends on it while building.
func (*Context) MenuPresentation ¶
func (_handle *Context) MenuPresentation() MenuPresentation
MenuPresentation returns how the window shows its popup menus (SetMenuPresentation).
func (*Context) Modifiers ¶
Modifiers returns the modifier keys held now, as the last key, pointer or modifier event said: a view showing each row's shortcut while Cmd is held reads it, and draws again as it changes.
func (*Context) OnShortcut ¶
OnShortcut declares a handler in the current context's parent scope: the window's, as OnWindowShortcut, at the root, else the parent element's focus subtree, as Element.OnShortcut.
func (*Context) OnWindowShortcut ¶
OnWindowShortcut declares a handler of the window's shortcut mods+key, which runs when c.Shortcut would report it, wherever c is in the tree: a component built deep in the view hears its keys while the focus is anywhere else, or nowhere, as one built at the root does. Elements around the focus that take the key, and overlays, still come first; one built in a dialog fires while the dialog shows, and one built behind it waits, as Shortcut does.
func (*Context) OpenURL ¶
OpenURL opens a URL in the default browser, or the app registered for its scheme, as a Link does. It returns at once; OpenURLThen tells what came of it.
func (*Context) OpenURLThen ¶
OpenURLThen opens a URL as OpenURL does, and done, unless nil, gets what came of it in a while, before a frame builds anew with what it changed: an error when no app could open the URL.
c.OpenURLThen(url, func(err error) {
if err != nil {
app.failed = url
}
})
func (*Context) PixelsPerDIP ¶
PixelsPerDIP returns the window's device-pixel density, at least 1. Use it to size application-owned GPU targets in pixels before drawing them at the same size in DIPs.
func (*Context) Preferences ¶
func (_handle *Context) Preferences() Preferences
Preferences returns the settings of the desktop that controls follow. A frame follows their changes.
func (*Context) ReadClipboard ¶
ReadClipboard returns the text on the clipboard, and WriteClipboard puts text there, for widgets that copy and paste themselves. Call them on the main thread: in the view, or in an input handler. WriteClipboardThen tells whether the text got there.
func (*Context) Region ¶
Region returns the user's regional formats (mygo.App.Region): the locale of the formats, the first day of the week and the hour cycle, which dates and times follow. A frame follows their changes.
func (*Context) Root ¶
Root returns the element holding the window's content: a column the size of the window.
func (*Context) Router ¶
isPath reports whether a link's target is a path within the app, as "/notes/42", "edit" or "?tab=info", rather than a URL with a scheme. Router returns the router whose page is being built, which a Link to a path without a scheme goes through, or nil outside one.
func (*Context) SetMenuPresentation ¶
func (_handle *Context) SetMenuPresentation(p MenuPresentation)
SetMenuPresentation sets how the window shows its popup menus: those of ContextMenu and Menu, the menus MyGo's widgets build with them, as a table's header and cell menus, and the editing menu of text inputs and selectable text. With PopoverMenus they draw in the window as PopoverMenu draws its menu, with its keys, focus and roles, so that an app with a look of its own shows no menu of the desktop's beside its own; with SystemMenus, the default, the system shows them. It stays until set again. PopoverMenu and PopoverMenuButton draw theirs in the window whatever it is. Only the menus MyGo builds follow it: the menu bar, the tray's menu and the Dock's stay the system's, and a web view's are the web view's own.
c.SetMenuPresentation(ui.PopoverMenus)
func (*Context) SetTheme ¶
SetTheme makes the frame use t, for the window's root and the widgets created after the call. Inside the children of a Themed, which keep its theme, t is for the root and the widgets after the Themed.
func (*Context) SetZoom ¶
SetZoom zooms the window's content by z, as a browser zooms a page: the view is laid out in a window 1/z its size and shown z times larger, drawn at the screen's resolution times z, so that text, icons, vectors and images stay as sharp as at that size natively, not a picture of the window scaled up. 1 shows the content at its size; the zoom stays until set again, and is clamped to between 0.25 and 5. A frame that sets another builds again at the new size before it shows.
What the view sees is zoomed: Size, TitleBar, Bounds and every length are in the content's DIPs, z of them to the window's. The pointer, text input, input methods, accessibility, context menus, drags and web views follow it. The window's own sizes are not zoomed: Window.SetContentSize and Window.ContentSize are in the window's DIPs, z times the content's.
c.SetZoom(app.zoom) // 1.25 for 125%
func (*Context) Shortcut ¶
Shortcut reports whether the key with exactly the modifiers mods was pressed, wherever the keyboard focus is, unless a focused element handled it first: a focused button or link takes Enter and Space, and a check box, switch or radio button Space, so that Enter can press a dialog's default button.
func (*Context) ShortcutRepeated ¶
ShortcutRepeated reports whether the key that the last Shortcut to report one took came as the auto-repeat of a key held down, as the web's KeyboardEvent.repeat: Context's, an Element's, a list's or an overlay's, and those that run OnShortcut's actions, which can ask it as they run. An action that steps while the key is held takes every key; a toggle takes the press alone, and lets the repeats go by:
if c.Shortcut(0, ui.KeyT) && !c.ShortcutRepeated() {
app.panel = !app.panel
}
It is false in a frame no shortcut took a key in yet.
func (*Context) Theme ¶
Theme returns the theme of the frame: the light or dark theme following the system's appearance, unless SetTheme replaced it. While the children of a Themed build, it is the Themed's theme.
func (*Context) TitleBar ¶
TitleBar returns the room the window controls take in a window with a hidden title bar (mygo.WindowOptions.TitleBarStyle), whose view draws the title bar under them: the traffic lights on macOS, the window buttons on Linux and Windows. It is zero in other windows and in full screen, where the controls hide. Keep clear of the controls, and let the title bar drag the window:
bar := c.TitleBar() ui.Row(c).Height(max(bar.Height, 32)).Padding(0, bar.Right, 0, bar.Left).DragWindow()
func (*Context) Toast ¶
Toast shows message near the bottom of the window for a few seconds, as the outcome of what the user just did:
if ui.Button(c, "Save").Clicked() {
app.save()
c.Toast("Saved")
}
A message already showing shows anew; others stack above it, three at most. It shows for as long as the pointer rests on it. Screen readers read it out. It is AddToast with message as the ID and the title.
func (*Context) ToastAction ¶
ToastAction shows message as Toast does, for longer, with a button of label that runs action, as Undo after deleting, and closes the toast; Tab reaches the button. action runs on the main thread, as the view does, which builds the frame again after it.
app.trash(note)
c.ToastAction("Note deleted", "Undo", func() { app.restore(note) })
func (*Context) Vibrancy ¶
Vibrancy reports whether the window shows its material (mygo.WindowOptions.Vibrancy) wherever the view draws no background: on macOS, and on Windows 11 22H2 and later in a window created with one. Elsewhere, what the view leaves transparent shows no material: draw a background there instead. The root draws the theme's background unless told otherwise; a sidebar over the material, beside opaque content:
if c.Vibrancy() {
c.Root().Background(ui.Transparent)
}
ui.Row(c).Fill().AlignItems(ui.Stretch).Children(func() {
sidebar := ui.Column(c).Width(240)
if !c.Vibrancy() {
sidebar.Background(c.Theme().Surface)
}
sidebar.Children(func() { app.sidebar(c) })
ui.Column(c).Grow(1).Background(c.Theme().Background).Children(func() { app.content(c) })
})
func (*Context) WindowActive ¶
WindowActive reports whether the window is drawn as active: the window the user's input goes to, as native apps draw it, while it or one of its flyouts has the keyboard (and always as Window.SetActiveAppearance keeps it). The built-in widgets fade their accent to gray in a window that is not, as AppKit's do (Theme.InactiveAccent), and macOS fades the window's material. A frame that reads it is drawn again as it changes; draw what shows which window has the user's input in a view of your own with it:
icon := c.Theme().Accent
if !c.WindowActive() {
icon = c.Theme().TextMuted
}
func (*Context) WindowHidden ¶
WindowHidden reports whether nothing of the window shows on screen, as the web's document.hidden: it is minimized, hidden, on another space or desktop, or covered by other windows, as far as the system tells (see the platform differences). A view that shows a clock, a price or what plays stops working while it is hidden, and refreshes as it shows again: the view builds once as it hides, and again as it shows, from the first time it asks. Frames that only move what shows wait while it is hidden anyway.
app.ticker.SetPaused(c.WindowHidden())
func (*Context) WriteClipboard ¶
func (*Context) WriteClipboardThen ¶
WriteClipboardThen puts text on the clipboard as WriteClipboard does, and done, unless nil, gets what came of it a moment later, before a frame builds anew with what it changed, as navigator.clipboard's writeText resolves or rejects: an error when the text did not get there, as when another app holds the clipboard, or a browser refuses a write the user did not act for (a press or a key, a moment before). A copy button shows "Copied" or "Failed" with it:
if ui.Button(c, "Copy").Clicked() {
c.WriteClipboardThen(link, func(err error) {
app.copied, app.copyFailed = err == nil, err != nil
})
}
type Current ¶
type Current uint8
Current is the item an element is the current one of, among those around it (Element.Current), as ARIA's aria-current says.
const ( // CurrentNone is not current. CurrentNone Current = iota // CurrentItem is the current item of a set, aria-current="true". CurrentItem // CurrentPage is the page the user is on: the last crumb of a // breadcrumb trail, or the link of a navigation bar to the page shown. CurrentPage // CurrentStep is the step of a process the user is at, as in a // wizard's steps. CurrentStep // CurrentLocation is the place shown, as in a flow chart or a map. CurrentLocation // CurrentDate is today in a calendar, and CurrentTime now in a // timetable. CurrentDate CurrentTime )
type Direction ¶
type Direction uint8
Direction is the direction an interface reads in: left to right, or right to left, as Arabic and Hebrew are, as Flutter's TextDirection, SwiftUI's LayoutDirection and CSS's direction say.
A window takes the direction of the app's language (package mygo sets it), and an element that of the element it is built in, unless it is given one (Element.Direction). Right to left, a Row lays its children out from the right, the Start of Justify, AlignItems and TextAlign is the right, a grid's columns go from the right, the logical edges (PaddingStart, MarginStart, Start, AnchorTopStart, ...) are on the right, horizontal scrolling starts at the right with its offsets counted from there, the vertical scroll bar is on the left, and the controls mirror what points along the line: arrows, chevrons, the fill of sliders and progress bars, switches, and where popups open. Paragraphs without a strongly directional character, as numbers, read right to left; the others take the direction of their first strong character either way.
As in Godot, the coordinate system is not mirrored: X still grows to the right, in Rect, in Draw's painter and in pointer positions, and what is physical stays so, as in CSS: Left, Right, Padding's left and right, AnchorTopLeft. Text, images and icons are not mirrored; draw what must point the other way after reading Context.Direction.
type DraggableOptions ¶
type DraggableOptions struct {
// Axis is the direction the element moves in: Horizontal, Vertical,
// or, when zero, both.
Axis Orientation
// Bounds, if set, holds the element's offset within it at rest: from
// X to X+W across, and from Y to Y+H down. The pointer drags the
// element past them less and less far, as iOS holds content pulled
// past its edges (Rubberband), and it goes back within them once let
// go; Rigid stops it at them.
Bounds *Rect
Rigid bool
// Snap, if set, chooses where the element comes to rest once let go,
// from where the throw would carry it (Project, held within Bounds):
// as the nearest of a sheet's heights or of a pager's pages (Nearest).
// A Snap returning its point lets the element glide there. Without
// Snap, the element rests where the pointer lets it go. What Snap
// returns along an axis the element does not move along is ignored.
Snap func(Point) Point
// Animation is how the element goes to rest, and to an offset the app
// sets: Smooth's spring when zero. A spring starts at the pointer's
// velocity as it lets go.
Animation Animation
}
DraggableOptions are how an element that the pointer drags moves (Element.Draggable), and where it comes to rest once let go.
type Easing ¶
Easing maps the time an animation has run, from 0 to 1 of its duration, to how far its value has gone, as CSS's timing functions do. Linear, EaseIn, EaseOut and EaseInOut are easings, and Bounce makes more.
func Bounce ¶
Bounce returns an easing that goes along ease and comes back, in the same time, as a pulse does.
func CubicBezier ¶
CubicBezier returns the easing of the cubic Bézier curve from (0, 0) to (1, 1) through the control points (x1, y1) and (x2, y2), as CSS's cubic-bezier(): x1 and x2 within 0 and 1.
type Effect ¶
type Effect interface {
// EffectMargin returns how far beyond the element's box, in DIPs
// across and down, the effect reads its content: the content renders
// that much around the box, as shadows painted beyond it, and reads as
// transparent further away.
EffectMargin() Point
// PaintEffect paints the element, its box in DIPs, from content, the
// element and its children rendered with p's scale, the box and the
// margin around it: inset is where the box's corner lies in content,
// in its pixels.
PaintEffect(p *Painter, box Rect, content *Bitmap, inset Point)
}
Effect draws an element from what it renders, as SwiftUI's colorEffect, distortionEffect and layerEffect do: package ui/shader's effects (shader.Effect), which change each pixel's color, move the pixels, or read the content anywhere. The element and its children render into a bitmap, which the effect then draws over the element's box, in its place. Hit testing, focus and accessibility do not change: only what shows.
type EffectBackdrop ¶
EffectBackdrop is where the backdrop of an effect lies (Painter. EffectBackdrop), as the renderers capture it: ToFrame maps a point in DIPs from a corner to the frame's pixels (x' = ToFrame[0]·(x, y, 1), y' = ToFrame[1]·(x, y, 1)); the texels start at Origin, in the frame's pixels, each Down pixels across, W×H of them.
type Element ¶
type Element struct {
// contains filtered or unexported fields
}
Element is a 16-byte, checked handle to a private pooled node. The zero value is absent. It expires before the next build pass, even in the same frame. Keep a Handle for persistent identity.
func Accordion ¶
Accordion creates sections, one above the other in a bordered box, that fn builds with AccordionItem. Each opens and closes on its own; Up and Down move the focus between their headers, as do Home and End.
ui.Accordion(c, func() {
ui.AccordionItem(c, "General", &app.general, func() { ... })
ui.AccordionItem(c, "Privacy", &app.privacy, func() { ... })
})
For one section open at a time, close the others as one opens:
for i, s := range sections {
open := app.section == i
if ui.AccordionItem(c, s.Title, &open, s.Build).Changed() {
app.section = -1
if open {
app.section = i
}
}
}
func AccordionItem ¶
AccordionItem creates a section of an Accordion: a header showing title, which a click opens and closes, as do Enter and Space, and below it what fn builds while *open is true. Changed reports a click.
func Autocomplete ¶
Autocomplete creates a text input editing *value, which suggests below it those of suggestions containing what was typed, those starting with it first: Up and Down move among them and Enter takes one, as does a click, while Enter on none is Submitted. Changed reports a change, typed or taken. Name it with Label.
ui.Autocomplete(c, &app.city, cities).Label("City")
func Avatar ¶
Avatar creates a picture of a person or a thing named name: the image, cropped to a circle, or the initials of name on a color it picks from it, as high as twice the font size. Assistive technology sees an image named name.
func BackButton ¶
BackButton creates a button going back in r's history, disabled at its start, as in the toolbar of Finder or a browser; a right click lists the pages before, to go back several. ForwardButton goes forward again.
func Badge ¶
Badge creates a short text in a pill, as a count of unread messages beside a sidebar's item.
func Breadcrumbs ¶
Breadcrumbs creates a path of items, as Finder's path bar and AppKit's path control, separated by chevrons: the items but the last are links, which a click chooses, as Enter does, setting *chosen to its index, which Changed reports. Long items shorten with an ellipsis as room runs short. Assistive technology sees links in a navigation landmark, which Label names, and the last item as the current page.
path := []string{"Macintosh HD", "Users", "ada", "Documents"}
if ui.Breadcrumbs(c, path, &app.chosen).Label("Path").Changed() {
app.open(path[:app.chosen+1])
}
func Button ¶
Button creates a button showing label. Ask Clicked whether it was clicked; give it other content with Children and an empty label.
func ButtonBase ¶
ButtonBase creates a button without a look: a row centering its children that takes the keyboard focus, and reports Clicked for the pointer, Enter and Space. Style it and give it children; Button is ButtonBase with the theme's look.
func Calendar ¶
Calendar creates a month's calendar choosing *date, as SwiftUI's graphical date picker, in the window's language, its weeks starting on the first day of the user's regional formats (Context.Region): a click chooses a day, as the arrows do while the calendar has the focus, Page Up and Page Down or its buttons move by months, and Home and End go to the first and the last day of the month. Changed reports a new date, which keeps the time of day and location of *date. Assistive technology reads the day chosen as the arrows move. Browse makes the keys and the buttons move without choosing.
func CheckboxBase ¶
CheckboxBase creates a check box without a look: a row that toggles *checked when clicked, or with Space while it has the focus, which Changed reports, and that assistive technology sees as a check box, checked or not. Draw its box from *checked; Checkbox is CheckboxBase with the theme's look.
func CheckboxGroup ¶
CheckboxGroup creates a check box over the check boxes that fn builds, indented below it, as a list of permissions: it is checked when they all are, mixed when some are, and a click, or Space while it has the focus, checks them all, or none when they all are. Changed reports a click. Assistive technology sees a check box, mixed while some are checked, and a group of the others named by label.
ui.CheckboxGroup(c, "Notifications", func() {
ui.Checkbox(c, &app.mail, "Mail")
ui.Checkbox(c, &app.calendar, "Calendar")
})
func CheckboxState ¶
func CheckboxState(c *Context, state *CheckState, label string) Element
CheckboxState creates a check box that can be mixed, with a label: a click, or Space while it has the focus, checks it, or unchecks it when it is checked, setting *state, and Changed reports a click. It shows a dash while mixed, and assistive technology sees it mixed. CheckboxGroup is one over the check boxes it holds.
func CheckboxStateBase ¶
func CheckboxStateBase(c *Context, state *CheckState) Element
CheckboxStateBase creates a check box without a look that can be mixed, as a "select all" box in a table's header, checked when every row is and mixed when some are: a row that sets *state to CheckOn when clicked, or with Space while it has the focus, or to CheckOff when it is CheckOn, which Changed reports, and that assistive technology sees as a check box, checked, unchecked or mixed. Draw its box from *state; CheckboxState is CheckboxStateBase with the theme's look.
all := ui.CheckOff
switch n := app.selectedCount(); {
case n == len(app.rows):
all = ui.CheckOn
case n > 0:
all = ui.CheckMixed
}
cb := ui.CheckboxStateBase(c, &all).Label("Select all")
cb.Children(func() { app.box(c, all) }) // a dash while mixed
if cb.Changed() {
app.selectAll(all == ui.CheckOn)
}
func Collapsible ¶
Collapsible creates a disclosure, as SwiftUI's DisclosureGroup: label beside an arrow, which a click opens and closes, as do Enter and Space, showing below it what fn builds while *open is true. The arrow turns and the content grows into view as it opens. Changed reports a click.
ui.Collapsible(c, "Advanced", &app.advanced, func() {
ui.Checkbox(c, &app.verbose, "Verbose logging")
})
func ColorPicker ¶
ColorPicker creates a picker of *color, as AppKit's color panel: a square choosing the saturation, across, and the brightness, up, of the hue its slider chooses below it, a slider of opacity, the color in hex, which the user edits, and swatches of common colors. The arrows move across the square while it has the focus, Up and Down changing the brightness and Left and Right the saturation. Changed reports a new color.
func ColorWell ¶
ColorWell creates a swatch of *color that opens a ColorPicker below it, as AppKit's color well: a click, Enter or Space opens it, and Escape or a click outside closes it. Changed reports a new color. Assistive technology sees a color well whose value is the color in hex; name it with Label.
func Column ¶
Column creates a container that lays its children out from top to bottom, stretched to its width.
func Combobox ¶
Combobox creates a combobox choosing *selected among options: a field showing the choice, whose text filters the options below it as the user types, those starting with it first, while a click or Down shows them all; a click showing them selects the choice, for typing to replace. Up and Down move among them and Enter chooses, as does a click; Escape closes them, and the text goes back to the choice when the field loses the focus. Changed reports a new choice. Name it with Label.
ui.Combobox(c, &app.font, fonts).Label("Font")
func DateInput ¶
DateInput creates a field showing *date in the user's regional formats, as 1/5/2026 in the United States, which a calendar below it changes. A click, Enter or Space opens the calendar, where a click chooses a day, as do the arrows and Enter; Page Up and Page Down, or its buttons, move by months, and Escape closes it. Changed reports a new date, which keeps the time of day and location of *date.
func DecimalInput ¶
DecimalInput creates a text input editing *value as an exact decimal between lo and hi, which the arrows Up and Down, and the buttons beside it, step by step: a NumberInput for amounts of money, which it never rounds. *value is written with exactly the decimals of step, as "1234.50"; lo and hi are written the same way, "" for no limit. What is typed applies as soon as it is a number in range, with '.' before its decimals and ',' between groups of three digits: "1,234.5" sets "1234.50", and shows so once the input loses the focus. Text with more decimals than step's (other than zeros), out of range or not a number leaves *value as it was and marks the input with Error, whose message an enclosing Field shows, until it is corrected. A value the app sets replaces what was typed. Changed reports a new value.
ui.DecimalInput(c, &app.amount, "0", "", "0.01")
func DialogBase ¶
DialogBase shows a dialog without a look over the window while *open is true: fn styles the backdrop covering the window, which centers the panel, and the panel, and builds the panel's content. Clicking the backdrop or pressing Escape sets *open to false, which Dismissed reports. It returns the panel, or nil while closed; Modal is DialogBase with the theme's look.
func EditableText ¶
EditableText shows *value as a text that the user edits in place, as a file's name in Finder: a double click on it, or Enter while it has the focus, shows a text input of it, with the text before its extension selected. Enter keeps what was typed, as moving the focus away does, and Escape goes back; Changed reports a new value.
In a List's or a Table's rows, the list keeps the focus and the text takes none: Enter on macOS, and F2, edit the text of the row chosen, while a double click on the row is Submitted; a click on the text of a row already chosen edits it, once a second click would no longer make a double click.
ui.Table(c, &app.files, cols, len(app.names), func(row, col int) {
if ui.EditableText(c, &app.names[row]).Changed() {
app.rename(row)
}
})
func Field ¶
Field creates a field: label, above the control that fn builds, or beside it in a Form. The label names the control for assistive technology, unless the control names itself, as a check box with its own text does, when it names the field around it; a click on the label focuses the control, or clicks a check box, a switch or a radio button. Description and Error add texts below the control, which describe it:
ui.Field(c, "Email", func() {
ui.TextInput(c, &app.email)
}).Description("For receipts.").Error(app.emailError)
The control is the first element fn builds that takes the focus, or a group of them, such as a RadioGroup.
func Fieldset ¶
Fieldset creates a group of the fields that fn builds, under legend, which names the group for assistive technology. Disabled disables them all. In a Form, their labels line up with those of the other fields.
ui.Fieldset(c, "Shipping", func() {
ui.Field(c, "Address", func() { ui.TextInput(c, &app.address) })
})
func FindBar ¶
FindBar creates a bar for finding text while *open is true, as Safari's and Xcode's: a field of *query, which takes the focus as the bar opens, how many matches there are of matches, previous and next buttons choosing *current among them, and Done. Enter in the field goes to the next match, Shift+Enter to the previous, as do Cmd+G and Shift+Cmd+G on macOS, F3 and Shift+F3 elsewhere, round the ends; Escape and Done close the bar. The app finds: it counts the matches of *query and shows match *current, which Changed reports moving. Assistive technology hears the count as it changes. While closed, it returns an element showing nothing.
func Form ¶
Form creates a column of the fields that fn builds (Field, Fieldset), whose labels sit in a column of their own, beside the controls, as in macOS's forms: aligned to the right, as wide as the widest, and level with the first line of their control.
ui.Form(c, func() {
ui.Field(c, "Name", func() { ui.TextInput(c, &app.name) })
ui.Field(c, "Size", func() { ui.Select(c, &app.size, sizes) })
})
func ForwardButton ¶
ForwardButton creates a button going forward in r's history, as BackButton goes back.
func Grid ¶
Grid creates a grid: its children fill its cells row by row, or go where ColumnStart and RowStart put them, spanning ColumnSpan columns and RowSpan rows. Columns and ColumnTracks set its columns; it adds rows as its children need them.
ui.Grid(c).Columns(3).Gap(12).Children(func() {
for _, p := range photos {
ui.Image(c, p).AspectRatio(1).Fit(ui.Cover)
}
})
func GridView ¶
func GridView(c *Context, s *GridState, n int, minWidth float32, height float32, item func(i int)) Element
GridView creates a scroll container of n items in a grid, as Photos' library and Finder's icon view, built with item(i): as many columns as fit items at least minWidth wide, which share the width left, and rows height high, built only as they show, so grids of millions of items are as fast as small ones. Gap spaces the items.
s keeps the place and says how items are chosen, or nil: with s.Selected, a click chooses an item, as the arrow keys do in two dimensions while the grid has the keyboard focus, with Home, End and the first letters of an item's Label.
app.photos.Selected = &app.photo
ui.GridView(c, &app.photos, len(photos), 140, 120, func(i int) {
ui.Image(c, thumbs[i]).Fit(ui.Contain).Grow(1)
}).Grow(1)
func Icon ¶
Icon creates an element showing an SVG as an icon: its shapes in the color of the text, which it takes from its ancestors as text does (TextColor), whatever colors the SVG has. It is as high as the font size (FontSize), keeping the SVG's aspect ratio, unless given a size, and does not stretch across a column. Icons are decorations that assistive technology does not see, unless Label names them.
ui.Row(c).Gap(6).Children(func() {
ui.Icon(c, save)
ui.Text(c, "Save")
})
func Image ¶
func Image(c *Context, src ImageSource) Element
Image creates an element showing a bitmap, or an SVG in its own colors (with the text color for its currentColor), by default at its size as DIPs, scaled to fit when given another size.
func Link ¶
Link creates a text that opens url in the browser when clicked, or Enter while it has the focus. In a page of a Router, a path without a scheme, as "/notes/42" or "edit", goes there in the router (Push). Inside a RichText it is a link within the paragraph; give it an empty label and Children to style parts of its text.
func List ¶
List creates a virtual list. The original row callback remains supported. Omit it to configure ItemKey and Selection, then call Rows.
func MenuButton ¶
MenuButton creates a button showing label and an arrow, which opens a menu below it that build fills with items, as the pointer goes down on it or for Enter, Space or Down while it has the focus (Element.Menu):
ui.MenuButton(c, "Sort by", func(m *ui.Menu) {
for _, by := range []string{"Name", "Date", "Size"} {
if m.Item(by).Checked(app.sort == by).Chosen() {
app.sort = by
}
}
})
PopoverMenuButton draws its menu in the window, with the theme's look.
func Meter ¶
Meter creates a bar showing value between lo and hi, as AppKit's level indicator and the web's meter: the theme's Success color, or Warning and Danger from the levels given, nil for none. Assistive technology sees a level indicator of that value; name it with Label.
ui.Meter(c, app.disk.Used, 0, app.disk.Size, &ui.MeterLevels{Warning: 0.8 * size, Critical: 0.95 * size}).Label("Disk")
func Modal ¶
Modal shows a dialog built by fn over a dimmed window while *open is true; clicking outside it or pressing Escape sets *open to false, which Dismissed reports.
func NumberInput ¶
NumberInput creates a text input editing *value as a number between lo and hi, which the arrows Up and Down, and the buttons beside it, step by step. What is typed applies as soon as it is a number in range, and shows rounded to the decimals of step once the input loses the focus. Changed reports a new value.
ui.NumberInput(c, &app.copies, 1, 99, 1)
func Outline ¶
func Outline[K comparable](c *Context, s *OutlineState[K], roots []K, children func(arg0 K) []K, row func(item K)) Element
Outline creates a list of items in a tree, as AppKit's outline view and SwiftUI's List of children: roots at the top, and below each item open its children, indented, which children returns, nil for an item without any. A click on an item's arrow opens or closes it, with all its children's children with Option (Alt). row builds the content of an item's row, after its arrow; Gap, Padding and the rest are a List's.
The outline builds only the rows in view, as a List does, so trees of any size are as fast as small ones. With s.List.Selected or Selection, rows are chosen as a List's, and while the outline has the focus, Right opens the item chosen or goes to its first child, and Left closes it or goes to its parent, with Option on macOS and Shift elsewhere, as in GTK, opening and closing all inside.
app.files.List.Selected = &app.file
ui.Outline(c, &app.files, []string{"/"}, func(dir string) []string {
return app.children[dir] // nil for files
}, func(path string) {
ui.Text(c, filepath.Base(path))
}).Grow(1)
func OutlineTable ¶
func OutlineTable[K comparable](c *Context, s *OutlineState[K], columns []TableColumn, roots []K, children func(arg0 K) []K, cell func(item K, col int)) Element
OutlineTable creates an outline whose rows are a Table's, as AppKit's outline view with columns: the first of columns shows the items' arrows, indented as they are deep, before what cell builds. It takes the columns, the sort and the keys of a Table, and those of an Outline.
ui.OutlineTable(c, &app.files, cols, roots, children, func(path string, col int) {
switch col {
case 0:
ui.Text(c, filepath.Base(path)).SingleLine()
case 1:
ui.Text(c, app.size(path))
}
})
func Popover ¶
Popover shows fn's elements in a panel below anchor while *open is true; clicking outside it or pressing Escape sets *open to false, which Dismissed reports.
func PopoverBase ¶
PopoverBase shows a panel without a look below anchor while *open is true: fn styles the panel and builds its content. Pressing outside the panel and the anchor, or Escape, sets *open to false, which Dismissed reports; the press goes on to what is under the pointer, as with the web's popovers. It starts at the anchor's start: its left, or its right right to left (Direction). Where there is no room below the anchor, the panel shows above it; a top margin keeps it apart from the anchor on either side. fn may place it elsewhere with AttachTo, as after the anchor:
panel.AttachTo(anchor, ui.AnchorEnd, ui.AnchorStart).MarginStart(6)
It returns the panel, or nil while closed; Popover is PopoverBase with the theme's look.
func PopoverMenuButton ¶
func PopoverMenuButton(c *Context, label string, build func(m *Menu), options ...PopoverMenuButtonOptions) Element
PopoverMenuButton creates a button showing label and an arrow, as MenuButton does, whose menu MyGo draws in the window with the theme's look, as PopoverMenu draws a context menu (Element.PopoverMenuButton):
ui.PopoverMenuButton(c, "Sort by", func(m *ui.Menu) {
for _, by := range []string{"Name", "Date", "Size"} {
if m.Item(by).Radio(app.sort == by).Chosen() {
app.sort = by
}
}
})
Its options place the menu and open it from the app, as Element.PopoverMenuButton's do.
func PrimaryButton ¶
PrimaryButton creates a button in the accent color, for the main action.
func Progress ¶
Progress creates a progress bar filled to value between 0 and 1; a negative value shows activity of unknown length. It fills from its start: the right right to left (Direction). Reverse fills it from the other side.
func Radio ¶
func Radio[T comparable](c *Context, selected *T, value T, label string) Element
Radio creates a radio button that selects value into *selected, with a label.
func RadioBase ¶
func RadioBase[T comparable](c *Context, selected *T, value T) Element
RadioBase creates a radio button without a look: a row that selects value into *selected when clicked, or with Space while it has the focus, which Changed reports, and that assistive technology sees as a radio button, on when *selected is value. Radio is RadioBase with the theme's look.
func RadioGroup ¶
RadioGroup creates a column of the radio buttons that fn builds (Radio, RadioBase), which are one stop of Tab: Tab goes to the one chosen, and the arrows choose among them, as do Home and End. Assistive technology sees a radio group; name it with Label. Make it a row with Row.
ui.RadioGroup(c, func() {
for _, size := range []string{"Small", "Medium", "Large"} {
ui.Radio(c, &app.size, size, size)
}
}).Label("Size")
func RangeSlider ¶
func RangeSlider(c *Context, low *float64, high *float64, lo float64, hi float64, step float64) Element
RangeSlider creates a slider of two knobs setting *low and *high between lo and hi, as a price range: each knob takes the focus, which Tab moves between, and the arrows, Home and End move it while it has the focus; a press on the track moves the knob nearest to it. A step above 0 snaps the values to lo and multiples of step from it, with tick marks. Changed reports a new value. Assistive technology sees two sliders, named by the RangeSlider's Label and "minimum" and "maximum".
func Rating ¶
Rating creates a row of max stars, as AppKit's rating level indicator, of which *value are filled: a click on a star sets it, a click on the star set clears it, and the arrows, Home and End change it while the rating has the focus. Changed reports a new value. Assistive technology sees a slider from 0 to max; name it with Label.
func RichText ¶
RichText creates a text whose spans differ in style, over the style of the text, which its methods and the elements around it set as for Text:
ui.RichText(c,
ui.Span{Text: "Saved "},
ui.Span{Text: "report.pdf", Weight: 600},
ui.Span{Text: " to "},
ui.Span{Text: "Documents", Color: t.Accent, Underline: true},
)
The spans wrap together as one paragraph, or several at newlines.
Text elements built in its Children (Text, Link, RichText) continue the paragraph after its spans, as HTML's inline elements do: each styles its own text over the paragraph's, and keeps its interaction (Clicked, Hovered, the focus, a Tooltip, assistive technology) with its words as its area. A link in a sentence:
ui.RichText(c).Children(func() {
ui.Text(c, "Read ")
ui.Link(c, "the guide", url)
ui.Text(c, " to get started.")
})
Only text elements go inside a text, and their sizes, padding, borders and corners do not apply; a background highlights their text.
func Row ¶
Row creates a container that lays its children out from left to right, centered vertically.
func Scroll ¶
Scroll creates a container that scrolls its children vertically. Give it a size, or Grow it within its parent.
func ScrollBoth ¶
ScrollBoth creates a container that scrolls its children both ways, as a canvas, a wide table or code does. Give it a size, or Grow it within its parent.
func ScrollHorizontal ¶
ScrollHorizontal creates a row that scrolls its children horizontally.
func SearchField ¶
SearchField creates a field for searching, editing *query: a magnifying glass, the text, and a button clearing it while it holds any, as Escape does then. Enter is its Submitted, and Changed reports a change. It shows Search while empty, or what Placeholder sets, and assistive technology sees a search field; name it with Label.
if ui.SearchField(c, &app.query).Label("Search mail").Changed() {
app.filter()
}
func Segmented ¶
Segmented creates a segmented control showing labels, of which *selected is the index of the one chosen, as a switch between views: a click chooses a segment, as do the arrows while it has the focus, and Changed reports a new choice. Assistive technology sees a radio group; name it with Label. For icons, build the segments with SegmentedBase.
ui.Segmented(c, &app.view, "List", "Grid").Label("View")
func Sidebar ¶
Sidebar creates a sidebar of the sections and the items that fn builds (SidebarSection, SidebarItem), as Finder's and Mail's, scrolling when they do not fit: a click chooses an item, whose ID *selected holds, and while the sidebar has the focus, Up and Down choose among its items, as do Home, End and typing the first letters of an item. It is one stop of Tab, and Changed reports a new choice. Give it a width:
ui.Sidebar(c, &app.mailbox, func() {
ui.SidebarSection(c, "Mailboxes", &app.mailboxes, func() {
ui.SidebarItem(c, "inbox", inboxIcon, "Inbox").Children(func() {
ui.Badge(c, "12")
})
ui.SidebarItem(c, "sent", sentIcon, "Sent")
})
}).Width(220)
Assistive technology sees a tree, whose sections hold their items.
func SidebarItem ¶
SidebarItem creates an item of a Sidebar choosing id, showing label after icon, nil for none. Add to it with Children, as a Badge.
func SidebarSection ¶
SidebarSection creates a section of a Sidebar under title, holding the items fn builds while *open is true, as Finder's: a click on the title shows and hides them, as does its arrow, which shows as the pointer rests on the title. A nil open keeps the section open.
func SliderBase ¶
SliderBase creates a slider without a look: dragging across its content box, within its padding, sets *value between lo and hi, as do the arrows, Home and End while it has the focus, by a hundredth of the range unless Step says otherwise; Changed reports a new value, and assistive technology sees a slider of that range. Draw its track and thumb where (*value-lo)/(hi-lo) puts them, and pad it by half the thumb's width to keep the thumb inside it. Right to left (Context.Direction), lo is at the right of the content box, as the arrows go: draw it mirrored.
s := ui.SliderBase(c, &app.volume, 0, 100).Height(24).PaddingX(12)
s.Draw(func(p *ui.Painter, r ui.Rect) {
x := r.X + 12 + (r.W-24)*float32(app.volume/100)
p.Fill(ui.Rect{X: r.X + 12, Y: r.Y + 10, W: r.W - 24, H: 4}, gray, 2)
p.Fill(ui.Rect{X: x - 12, Y: r.Y, W: 24, H: 24}, blue, 12)
})
Vertical makes it go up from lo at the bottom. Slider is SliderBase with the theme's look.
func Spacer ¶
Spacer creates an empty element that takes the free space of its row or column, pushing its siblings apart.
func Spinner ¶
Spinner creates an indicator of work of unknown length, as AppKit's spinning progress indicator: spokes turning, as high as the font size, in the theme's muted text color, or the color TextColor gives it, as one on a chosen row of a list needs. Assistive technology sees a progress indicator of unknown length; name it with Label.
func Split ¶
Split lays out first and second side by side, with a divider between them that the user drags to resize them, or moves with the arrows once it has the keyboard focus: *size is the width of first, which the divider keeps 40 DIPs from either edge. With less room than that, first gives way, keeping *size for when there is room again. Changed reports a move. Right to left (Direction), first is on the right. SplitReset makes a double click on the divider put first back at a size the app chooses.
ui.Split(c, &app.sidebar, app.files, app.editor).Fill()
func SplitPercent ¶
SplitPercent is Split with *p the percentage of the room first takes, from 0 to 100, so that both panes grow and shrink with the room, in proportion.
ui.SplitPercent(c, &app.sidebarPercent, app.files, app.editor).Fill()
func SplitVertical ¶
SplitVertical is Split with first above second, *size its height.
func SplitVerticalPercent ¶
SplitVerticalPercent is SplitPercent with first above second.
func StepSlider ¶
StepSlider creates a slider setting *value to lo or a multiple of step from it, up to hi, with a tick mark at each, as AppKit's sliders with tick marks: dragging snaps to them, and the arrows step by step.
func Stepper ¶
Stepper creates a pair of arrows changing *value by step between lo and hi, as AppKit's stepper beside a field: a click on an arrow steps up or down, as do Up and Down while the stepper has the focus, and holding an arrow keeps stepping. Changed reports a new value. Assistive technology sees a spin button; name it with Label.
func SwitchBase ¶
SwitchBase creates a switch without a look: CheckboxBase, which assistive technology sees as a switch. Switch is SwitchBase with the theme's look.
func Table ¶
func Table(c *Context, s *ListState, columns []TableColumn, n int, cell func(row int, col int)) Element
Table creates a table of n rows under a header of columns, whose rows are a List's: it builds only those in view, cell building the content of a row's column, usually a Text. Rows are as high as their tallest cell, and at least as high as the header.
s keeps the place of the rows and says how they behave, as a List's, or nil: with s.Selected, a click chooses a row, as Up, Down, Home and End do while the table has the keyboard focus, Changed reports a new choice, and Submitted a double click or Enter on it; with s.Selection, the user chooses several. A row s.Header names spans every column, cell building it as column 0, and stays at the top while the rows of its section scroll under it.
The user resizes columns by dragging the edges of their headers, and moves them by dragging the headers, which s.Columns keeps; columns wider than the table scroll sideways, the header with them. With s.Sort, a click on the header of a Sortable column sorts the rows by it; with s.SortBy, a Cmd-click or a Shift-click sorts by it after the others; with s.HeaderMenu, the header has a context menu.
cols := []ui.TableColumn{{Title: "Name", Sortable: true}, {Title: "Size", Width: 90, Align: ui.End, Sortable: true}}
app.files.Selected, app.files.Sort = &app.file, &app.sort
if ui.Table(c, &app.files, cols, len(files), func(row, col int) {
f := files[row]
switch col {
case 0:
ui.Text(c, f.Name).SingleLine()
case 1:
ui.Text(c, f.Size())
}
}).Grow(1).Submitted() {
app.open(files[app.file])
}
func Tabs ¶
Tabs creates a row of tabs showing labels, of which *selected is the index of the one chosen. A click chooses a tab, as do the arrows, Home and End while one has the keyboard focus, which follows the choice:
ui.Tabs(c, &app.tab, "General", "Appearance", "Advanced")
switch app.tab {
case 0:
app.general(c)
…
}
Changed reports a new choice.
func TextAreaBase ¶
TextAreaBase creates a multi-line text input without a look, editing *value: TextArea without its padding, background, border and corners.
func TextAreaBuffer ¶
func TextAreaBuffer(c *Context, value *TextBuffer) Element
TextAreaBuffer creates a multiline control editing indexed storage. Ordinary edits and native queries never materialize the whole document. Layout retains the paragraphs in view, as TextArea does.
func TextAreaBufferBase ¶
func TextAreaBufferBase(c *Context, value *TextBuffer) Element
func TextInputBase ¶
TextInputBase creates a single-line text input without a look, editing *value: TextInput without its padding, background, border and corners.
func TextInputBuffer ¶
func TextInputBuffer(c *Context, value *TextBuffer) Element
TextInputBuffer creates a single-line control editing indexed storage. It shares TextInput's selection, composition, undo and styling behavior.
func TextInputBufferBase ¶
func TextInputBufferBase(c *Context, value *TextBuffer) Element
TextInputBufferBase and TextAreaBufferBase are the unstyled buffer controls.
func Themed ¶
Themed creates a column whose children build with t, as SetTheme has the whole window build: the widgets inside take their colors and metrics (Spacing, Radius, FontSize) from t, Context.Theme returns t while they build and Painter.Theme while they paint, and the popovers, menus, tooltips and dialogs they open take t too. The column paints t's Background, and the text inside takes t's Text color, FontSize and Font, as the root has the window's theme's; Background(ui.Transparent) keeps what is behind it instead. The root, and what is built after the column, keep the window's theme. Light beside dark, as a theme picker previews them:
ui.Row(c).Fill().AlignItems(ui.Stretch).Children(func() {
for _, t := range []*ui.Theme{ui.LightTheme(), ui.DarkTheme()} {
ui.Themed(c, t).Grow(1).Padding(16).Gap(8).Children(func() {
ui.Text(c, "Preview")
ui.Button(c, "OK")
})
}
})
A nil t makes it a Column.
func TimeInput ¶
TimeInput creates a field of the time of day of *tm, in the hour cycle of the user's regional formats (Context.Region): 15:04, or 3:04 PM with the window's language's names of the halves of the day, before the hours where the language writes them so (下午3:04). Its hours, minutes and half of the day each take the focus, as the segments of AppKit's date picker: Up and Down step the one with the focus round the clock, digits typed set it, going on to the minutes once the hours are typed, the first letter of a half of the day chooses it, and Left and Right move between them. Changed reports a new time, which keeps the date and the location of *tm. Assistive technology sees spin buttons, named after the field's Label and "hours", "minutes" and "AM/PM". It reads left to right in an interface laid out right to left too, as times are written there.
ui.TimeInput(c, &app.alarm).Label("Alarm")
func ToastViewportBase ¶
ToastViewportBase builds the window's toasts without a look, in place of the theme's: fn styles viewport, a column covering the window that the pointer goes through, which holds them at its bottom, and builds each of toasts with ToastBase, giving it the look of its Type and Data. toasts are those showing, the newest three, oldest first. Call it once in the view, wherever. Toasts in the bottom right corner:
ui.ToastViewportBase(c, func(viewport ui.Element, toasts []ui.Toast) {
viewport.Padding(16).AlignItems(ui.End).Gap(8)
for _, t := range toasts {
toast := ui.ToastBase(c, t)
toast.Root.Row().Gap(12).Padding(10, 14).Radius(8).Background(surface)
toast.Root.Children(func() {
ui.Text(c, t.Title).Grow(1)
toast.CloseButton().Label("Close").Children(func() { ui.Icon(c, x) })
})
}
})
The time of the toasts stops while the pointer rests on viewport or the keyboard focus is in it with the window's, and runs on while the window is in the background. viewport stays while no toast shows, for the last one to go with an exit transition. It returns viewport.
func Toggle ¶
Toggle creates a button that stays pressed while *on, as Bold in an editor's toolbar: a click presses it or lets it go, as does Space while it has the focus, and Changed reports a change. Give it other content, such as an icon, with Children and an empty label, and name it with Label:
ui.Toggle(c, &app.bold, "").Label("Bold").Children(func() { ui.Icon(c, boldIcon) })
func ToggleBase ¶
ToggleBase creates a toggle button without a look: a row that turns *on over when clicked, or with Space while it has the focus, which Changed reports, and that assistive technology sees as a toggle button, pressed while *on. Toggle is ToggleBase with the theme's look.
func ToggleGroup ¶
ToggleGroup creates a row of the toggles and buttons that fn builds, drawn joined as the segments of one control, as Bold, Italic and Underline. They are one stop of Tab, among which the arrows move the focus, as in a toolbar; name the group with Label.
ui.ToggleGroup(c, func() {
ui.Toggle(c, &app.bold, "B")
ui.Toggle(c, &app.italic, "I")
}).Label("Style")
func TokenField ¶
TokenField creates a field of tokens, as of tags or the recipients of a mail: *tokens shows as chips, each with a button taking it out, before an input where Enter or a comma adds what was typed, and Backspace in it while empty takes out the last. The suggestions containing what was typed show below it, those not already tokens: Up and Down move among them, and Enter or a click adds one. Changed reports a change; name it with Label.
ui.TokenField(c, &app.tags, allTags).Label("Tags")
func Toolbar ¶
Toolbar creates a row of the controls that fn builds, as along the top of a window: buttons, toggles, toggle groups, segmented controls and menu buttons, which take no face of their own until hovered. It is one stop of Tab, and Left and Right move the focus among its controls, Home and End to the first and the last; assistive technology sees a toolbar, which Label names. Controls that do not fit go, from the last, into a menu at its end, where choosing one clicks it. Spacer pushes those after it to the end.
ui.Toolbar(c, func() {
ui.ToggleGroup(c, func() {
ui.Toggle(c, &app.bold, "Bold")
ui.Toggle(c, &app.italic, "Italic")
})
ui.Spacer(c)
if ui.Button(c, "Share").Clicked() {
app.share()
}
}).Label("Format")
func TooltipBase ¶
TooltipBase shows a tip without a look by anchor: fn styles the tip and builds its content. It shows once the pointer has rested on anchor for 0.6 seconds, at once as anchor gets the keyboard focus from the keyboard, and at once too within 0.4 seconds of another tip going, as the pointer moves along a toolbar; the theme's TooltipDelay changes both. It goes as the pointer leaves anchor or presses it, and with Escape, until the pointer comes back or the focus does. Over elements inside one another, the innermost one's tip shows; one shows at a time.
The tip goes above anchor, centered, or below it where there is no room above; fn may place it elsewhere with AttachTo, as after it:
ui.TooltipBase(c, b, func(tip ui.Element) {
tip.AttachTo(b, ui.AnchorEnd, ui.AnchorStart).MarginStart(6)
tip.Padding(4, 8).Radius(6).Background(dark).TextColor(light)
tip.Children(func() { ui.Text(c, "Share") })
})
The pointer goes through the tip, and assistive technology sees it as a tooltip, which it does not read: give anchor a Description to tell what the tip does. It returns the tip, or nil while it does not show; Element.Tooltip is TooltipBase with the theme's look.
func Tree ¶
Tree creates a tree, whose items TreeItem builds in fn. While an item has the keyboard focus, Up and Down move it to the items around, Home and End to the first and the last, Right opens the item or moves to its first child, Left closes it or moves to its parent, and typing the first letters of an item moves to it. The tree is one stop of Tab.
ui.Tree(c, func() {
ui.TreeItem(c, "src", &app.srcOpen, func() {
ui.TreeItem(c, "main.go", nil, nil)
})
ui.TreeItem(c, "go.mod", nil, nil)
})
Tree is TreeBase with the theme's look.
func TreeItem ¶
TreeItem creates an item of a Tree showing label, inside the item it is built in. children builds the items inside it, which show while *open is true; nil children, or a nil open, makes a leaf. A click on its arrow opens or closes it; Clicked reports a click elsewhere on it, or Enter, for choosing it, which Selected shows.
func Video ¶
func Video(c *Context, p *VideoPlayer) Element
Video creates an element showing a player's video, by default at its size as DIPs, scaled to fit when given another size, as Image shows a bitmap:
//go:embed waves.gif var wavesGIF []byte d, err := ui.NewGIFDecoder(wavesGIF) ... app.waves, err = ui.NewVideoPlayer(d) app.waves.SetLoop(true) ui.Video(c, app.waves).Fill().Fit(ui.Cover)
The video moves on only while the view builds it and some of the window shows: one that went out of the view, or a window out of sight, goes on from where it stood. Each frame of the video is a frame of the window, which After asks for as it comes due. While the desktop asks for less motion (Preferences.ReduceMotion), it shows its first frame and does not play.
func WebView ¶
func WebView(c *Context, v NativeWebView) Element
WebView shows a web view, made with mygo.Window.NewWebView, in the element's content box. A web view has no size of its own: the element stretches across its container (AlignSelf(Stretch)), and takes the room along it with Grow or a size:
ui.Row(c).Fill().Children(func() {
sidebar(c)
ui.WebView(c, app.docs).Grow(1)
})
The web view shows while a frame builds its element and hides when one does not, keeping its page: a view switching tabs builds the web view of the tab shown. The element paints a hole through the window's content (the web view is under it, the system's own view), as rounded as its Radius and cut by the scroll containers and clips around it, so that what paints after it shows over the page: its children, popovers, menus, dialogs, tooltips and toasts. The page takes the pointer where it shows and nothing painted over it takes it, and the keyboard once clicked, focused (mygo.WebView.Focus) or tabbed into: Tab stops at the element. The keys the page leaves unhandled come to the native UI as if the element had the focus, which the shortcuts around it and the window's see. Its background and border paint around the page, which its opacity fades, and assistive technology finds the page inside it.
func (Element) Absolute ¶
Absolute takes the element out of its parent's layout and places it with Top, Right, Bottom and Left relative to the parent's padding box, above its siblings. As in CSS, that box is inside the parent's border but holds its padding: Top(0) puts the element just below the border, whatever the padding.
func (Element) Access ¶
func (_handle Element) Access(fn func(n *platform.AccessNode)) Element
Access has fn describe the element further to assistive technology, as it builds the element's node, only while assistive technology reads the window: what costs too much to give every frame, as the text of a large document. The node is a type internal to this module, so only its packages describe elements so, as package ui/editor does.
func (Element) AccessDisabled ¶
AccessDisabled tells assistive technology that the element and those inside it are unavailable when off is true, as HTML's aria-disabled does, while they keep the keyboard focus, their place in the Tab order, the pointer and their look: a screen reader still reaches them and reads them, as dimmed or unavailable, with their Description, which can say why. It is for what the user must still find while it cannot be used, as a menu item whose action is blocked, a tab disabled but still in the arrows' order, or a submit button while the form is not valid:
del := ui.Button(c, "Delete project").AccessDisabled(app.locked)
if app.locked {
del.Description("Unlock the project to delete it")
}
if del.Clicked() && !app.locked {
app.deleteProject()
}
It only tells: clicks and keys still reach the element, which the view ignores while it is unavailable, and it does not dim it, which the view styles itself if it wants. Assistive technology focuses it, but neither presses nor edits it. Disabled does all of it at once: no clicks, no focus, and half the opacity.
func (Element) AccessHidden ¶
AccessHidden leaves the element and those inside it out of what assistive technology reads when hide is true, while they still show, as HTML's aria-hidden does: none of them is in its tree, their text names no element around them, and it can neither press, focus nor edit them. The pointer and the keyboard still reach them, unless they IgnoreInput too, which makes them inert, as HTML's inert does; without it, keep the keyboard focus out of them, where assistive technology cannot follow.
What shows but is not there to read is so read once, or not at all: a page sliding out beside the one that replaces it, the cards peeking from behind the front one of a stack, a copy of a text fading into another:
if app.leaving >= 0 {
page(c, app.leaving).Absolute().Translate(-x, 0).IgnoreInput(true).AccessHidden(true)
}
page(c, app.tab).Translate(width-x, 0)
RoleNone leaves out the element but not those inside it.
func (Element) AccessSelected ¶
AccessSelected tells assistive technology whether the element, a tab, an option, a row, a cell or an item of a tree of your own, is selected, as ARIA's aria-selected, without the accent background and text color Selected paints: for one that shows its choice its own way, as a tab underlined or a row with a check mark.
tab := ui.ButtonBase(c).Role(ui.RoleTab).Label(name).AccessSelected(i == app.tab)
if i == app.tab {
tab.Bold()
}
It sets the state Selected sets, which Checked also sets on these roles, so every platform reads it as Selected's: a row or a cell saying whether it is selected, false or true, is one its table or grid chooses among others (Selectable). It only tells: the view shows the choice, and changes it as the element is clicked.
func (Element) ActiveDescendant ¶
ActiveDescendant tells assistive technology that d has the keyboard focus while the element does: the option the arrows are on in a list or a menu that keeps the focus itself, as a combobox's input does. Call it once d is built, inside the element or in its popup.
func (Element) AlignContent ¶
AlignContent places the lines of a wrapping container across its main axis, as CSS's align-content does: Start (the default), Center, End, Stretch, SpaceBetween, SpaceAround or SpaceEvenly. In a grid it places the rows, which stretch when it is not set.
func (Element) AlignItems ¶
AlignItems places the children across the main axis.
func (Element) AlignSelf ¶
AlignSelf places the element across its parent's main axis, overriding the parent's AlignItems; in a grid, it places the element in its cell vertically.
func (Element) Animate ¶
Animate returns a value that moves to target over d, easing out, and keeps frames coming while it moves; key tells apart the animations of the element. The value starts at the first target. When the desktop asks for less motion (Preferences.ReduceMotion), it goes to target at once. AnimateTo takes springs and delays too.
func (Element) AnimateColor ¶
AnimateColor returns a color that goes to target as a says, mixed with premultiplied alpha as transitions mix colors, so that a color fading from transparent keeps its hue, in sRGB or, with a's Oklab, in Oklab; key tells apart the element's animated colors. It starts at the first target. As changing colors moves nothing, colors still change smoothly while the desktop asks for less motion; DisableAnimations shows them at once.
func (Element) AnimatePose ¶
AnimatePose moves the element to p as a says, after its own transform (Transform), and fades it, and returns the element. The element keeps going in frames that only paint, without building the view, as Core Animation and the Web Animations API run transforms and opacity: the cheapest motion there is, which a view large or slow to build keeps smooth. The pointer, carets and overlays follow it as they follow transforms. While the desktop asks for less motion, it moves at once, and only fades smoothly.
card.AnimatePose(ui.Pose{Y: lift, Scale: 1.02}, ui.Snappy)
It starts at the first pose: an element that the frame before did not pose, as one built for the first time, shows at p at once, and moves only when a later frame poses it elsewhere. To come in from a pose, as a flyout's panel rising as it shows, pose the element there in one build, ask for another frame (Context.Invalidate), and pose it at its place in the next:
entered := ui.Local(panel, "entered", func() bool { return false })
p := ui.Pose{}
if !*entered {
p, *entered = ui.Pose{Y: 8, Fade: 1}, true
c.Invalidate()
}
panel.AnimatePose(p, ui.Snappy)
An element appearing in a parent that the frame before showed comes in with the Enter of its Transition too.
func (Element) AnimateTo ¶
AnimateTo returns a value that goes to target as a says, and keeps frames coming while it moves; key tells apart the animated values of the element, which Animate, AnimateWith and Spring share. The value starts at the first target (Jump sets it elsewhere first). A new target on the way, or a new kind of Animation, takes over from where the value is: a spring keeps its velocity, even that of a curve. When the desktop asks for less motion (Preferences.ReduceMotion), the value goes to its target at once, unless a's NonMotion says it moves nothing, as a fade:
op := e.AnimateTo("fade", target, ui.Animation{Duration: 200 * time.Millisecond, NonMotion: true})
func (Element) AnimateWith ¶
AnimateWith returns a value that moves to target over d as Animate does, along ease.
func (Element) Arrived ¶
Arrived reports whether the value animated under key came to rest at its target in this frame, after moving there: true in that frame only, for the view to go on, as by removing what faded out.
func (Element) AspectRatio ¶
AspectRatio makes the height the width divided by r.
func (Element) Attach ¶
Attach takes the element out of its parent's layout, as Absolute does, and puts its point self on the point at of the parent's padding box: Attach(ui.AnchorTopRight, ui.AnchorCenter) centers a badge on the top right corner of its parent, and Attach(ui.AnchorBottomRight, ui.AnchorBottomRight) puts a button in the bottom right corner. Top, Right, Bottom and Left then move it from there; the element keeps its own size.
func (Element) AttachEdgeMargin ¶
AttachEdgeMargin sets how far an element placed with AttachTo stays from the window's edges, v DIPs on each side, where it is 4 unless set: a panel that must not touch the edges of a small window keeps 12 from them, as the inset-modified containing block of CSS Anchor Positioning keeps a positioned box inside the insets given to it. It is the room the element flips and moves to stay in, and that one scrolling is limited to.
func (Element) AttachTo ¶
AttachTo takes the element out of its parent's layout, as Attach does, and puts its point self on the point at of target's box, wherever target is in the window: built in an Overlay, a panel goes below a button with AttachTo(button, ui.AnchorBottomLeft, ui.AnchorTopLeft), and to its right with AttachTo(button, ui.AnchorRight, ui.AnchorLeft). Where it would overflow the window, it goes to the other side of target, or the other way along it, if that overflows less, then moves along target into the window. Its margins keep it apart from target: a top margin below it, and above it as it goes there. Top, Right, Bottom and Left then move it; the element keeps its own size.
The element is target's popover: its elements follow target as Tab moves, and a press on target is not outside it (PressedOutside). Build target before it, in the same frame. AttachedAnchors tells the side it went to.
func (Element) AttachedAnchors ¶
AttachedAnchors returns the points of its target's box and of its own that AttachTo put together as the layout placed the element: those asked for, or, where it went to the other side of target or the other way along it to stay in the window, those across or down from them, as Floating UI's placement: AnchorTop and AnchorBottom for a panel asked below its button, with AttachTo(button, ui.AnchorBottom, ui.AnchorTop), that went above it. Start and end anchors stay start and end ones. The view reads the last frame's, which are those asked for until the element is laid out, as in the frame it first shows; Draw reads this frame's. From that first frame, AttachedOrigin puts the element's transform origin on its own point, and a Motion's Flip mirrors its Enter and Exit, on the side the layout chose. An element not attached to another returns its Attach anchors, or AnchorTopLeft twice without them.
func (Element) AttachedOrigin ¶
AttachedOrigin sets the transform origin on the element's own point that AttachTo puts on its target, on whichever side of it the layout puts the element (AttachedAnchors), from the frame it shows: a tooltip or a menu scaling in, or out, grows from the edge nearest its trigger, as Radix's popper transform origin. It replaces TransformOrigin on an element attached to another.
func (Element) AutoComplete ¶
func (_handle Element) AutoComplete(kind AutoComplete) Element
AutoComplete tells assistive technology what the suggestions of a text input or a combobox of your own complete as the user types, as ARIA's aria-autocomplete: AutoCompleteList for a popup of the values matching what was typed, which screen readers announce with the field so that the user knows to look there, AutoCompleteInline for the text completed in place. It only tells it: the view shows the suggestions itself, as in ComboboxBase's popup. Combobox, Autocomplete, and a TokenField with suggestions, tell AutoCompleteList themselves; AutoCompleteNone takes it back.
func (Element) AutoFocus ¶
AutoFocus gives the element the keyboard focus in the frame it appears, as the first field of a dialog.
func (Element) BackfaceHidden ¶
BackfaceHidden hides the element, and takes it from the pointer, while its 3D transform turns its back to the viewer, as CSS's backface-visibility: hidden: the two faces of a card turning over, the back turned 180 degrees more than the front, show one at a time.
front.RotateY(turn).Perspective(800).BackfaceHidden() back.RotateY(turn + 180).Perspective(800).BackfaceHidden()
func (Element) Background ¶
Background fills the element, in place of a gradient.
func (Element) Balance ¶
Balance wraps the element's text in lines of about the same length, as CSS's text-wrap: balance does: a heading or a short callout that takes two lines takes two of half its length each, rather than a full line and a word alone on the next. The text takes as many lines as it would without it, at the width layout gives it, and keeps its alignment within that width. Each paragraph is balanced on its own, once a layout, as the text system keeps it.
func (Element) Basis ¶
Basis sets the size along the parent's main axis before growing or shrinking.
func (Element) BasisPercent ¶
BasisPercent sets the basis as a percentage of the parent's size along its main axis.
func (Element) Blur ¶
Blur blurs the element, with its children, by sigma DIPs, the standard deviation of a Gaussian, as CSS's filter: blur() does: what it draws spreads that far around, transparent beyond, on the GPU. It renders into a bitmap first, as Effect does, about 3 sigma larger each way, and an element with an Effect draws through it instead. Hit testing, focus and accessibility do not change: only what shows.
func (Element) Border ¶
Border draws a border of width DIPs inside the element's edges, on every side; BorderWidth sets different widths. As in CSS, the border takes room within the element's size: the padding and the children are inside it.
func (Element) BorderColor ¶
BorderColor sets the color of the border.
func (Element) BorderConicGradient ¶
func (_handle Element) BorderConicGradient(g ConicGradient) Element
BorderConicGradient paints the element's border (Border, BorderWidth) with a conic gradient around the element, in place of its color: a ring of colors, as SwiftUI's strokeBorder with an AngularGradient draws.
ui.Box(c).Size(120, 80).Radius(16).Border(4, ui.Color{}).BorderConicGradient(ui.ConicGradient{Stops: rainbow})
func (Element) BorderEndWidth ¶
func (Element) BorderLinearGradient ¶
func (_handle Element) BorderLinearGradient(g LinearGradient) Element
BorderLinearGradient paints the element's border (Border, BorderWidth) with a linear gradient across the element, in place of its color.
func (Element) BorderStartWidth ¶
BorderStartWidth and BorderEndWidth set the width of the border on the side lines start and on the other, as PaddingStart does: a line between a sidebar and the content is BorderEndWidth(1) on the sidebar.
func (Element) BorderStyle ¶
func (_handle Element) BorderStyle(s BorderStyle) Element
BorderStyle sets whether the border is solid, as by default, or dashed.
func (Element) BorderWidth ¶
BorderWidth sets the widths of the border on each side, CSS style: all sides, vertical and horizontal, or top, right, bottom and left. A line below a header:
ui.Row(c).BorderWidth(0, 0, 1, 0).BorderColor(t.Border)
func (Element) BottomPercent ¶
func (Element) Bounds ¶
Bounds returns the previous frame's transformed bounding rectangle in window DIPs, the content's when zoomed (Context.SetZoom); it is empty for an element the previous frame lacked. LayoutBounds returns its box before visual transforms.
func (Element) Browse ¶
Browse lets the user move about a Calendar without choosing a day: its buttons and Page Up and Page Down only show other months, and the arrows, Home and End only move among the days, until a click, Enter or Space chooses one, as in a date input's calendar. Changed then reports only a day chosen, as a calendar in a popover that closes when the user picks a day needs. The calendar goes back to *date as the app sets another.
func (Element) Busy ¶
Busy tells assistive technology whether the element's content is about to change, as a region loading, or one updated in several steps: screen readers wait until it is no longer busy to read what changed in it. A placeholder standing in for the content, as a skeleton or a spinner, says what is happening (a RoleStatus labelled "Loading").
func (Element) Cache ¶
Cache keeps what the element paints, with its children, in a bitmap of the GPU that frames draw as one image, as Flutter's RepaintBoundary and SwiftUI's drawingGroup do: for a still subtree that costs much to draw, as a card of gradients, blurred images and large shadows, under or around a drawing that moves. A frame redrawing where something above or next to it changed then draws the bitmap there, not each of its layers, and moving, scaling or rotating the element (Translate, Scale, Rotate, AnimatePose) moves the bitmap, not what it holds.
The bitmap is the size of the element's box at the window's scale, and of what it and those inside it paint around it: shadows, focus rings, and children beyond the box that it does not clip, as Draw callbacks paint (within the box and the shadows' reach). It is drawn again when what the subtree paints changes: built anew with other content, laid out at another size, at another scale or in another theme, or as something inside it moves on its own (Painter.AnimationFrame, a pose, a transition), as then it is every frame. Painting the window still paints the subtree, to tell; frames that only paint the drawings that asked for them (Painter.AnimationFrame, Painter.After) do not.
As in an effect's bitmap (Effect), its text is smoothed in grayscale where the subtree paints no opaque background under it, web views inside it do not show, and a subtree larger than 8192 pixels across is drawn as it is. The bitmap is drawn at the window's scale, so that turned, or scaled up by a transform, it shows a little softer than the shapes it holds would.
func (Element) CaretColor ¶
CaretColor sets the color of the insertion caret of the text inputs in the element, as CSS's caret-color does, a field's own text color for one; the theme's accent is the color elsewhere.
func (Element) CaretWidth ¶
CaretWidth sets this input's painted caret width in DIPs for this build. It defaults to one DIP. Positive widths are rounded to device pixels, at least one pixel wide; zero and negative widths hide the caret. It does not change text layout, input-method candidate bounds or caret blinking. Other elements are unaffected.
func (Element) Changed ¶
Changed reports whether this widget's value changed in this build pass, by the input it took as its constructor returned.
func (Element) Checked ¶
Checked tells assistive technology whether the element, as a check box, switch, radio button, toggle button or menu item of your own, is on, or whether an option (RoleOption) is selected. Bases set it from their value.
func (Element) ChildExit ¶
ChildExit says where the children of the element that leave in this frame go, in place of the Exit of their Transitions: those whose Transition has an Exit, which are copied as they go. It suits an exit decided as they leave, as a calendar, a wizard or a carousel stepping forward or back, whose page going goes the way of the step that sent it, even when the step turned around in the frame it went:
dir := float32(app.dir) // 1 forward, -1 back
ui.Box(c).Fill().ChildExit(ui.Motion{X: -40 * dir}).Children(func() {
ui.Column(c.Key(app.page)).Absolute().Fill().Transition(ui.ElementTransition{
Enter: &ui.Motion{X: 40 * dir},
Exit: &ui.Motion{X: -40 * dir},
})
})
Copies already on their way go on as they went.
func (Element) Children ¶
Children builds children with the same context, scoped to this element. An absent element skips fn. Expired elements are diagnosed in development.
func (Element) ClickModifiers ¶
ClickModifiers returns the modifier keys held as the element was last clicked, none for a click by the keyboard: with Clicked, a click with Shift or Cmd does something else, as extending a choice.
func (Element) Clicked ¶
Clicked reports whether the element was clicked, with the primary button or by Enter or Space while focused, since the last frame.
func (Element) ClipInset ¶
func (_handle Element) ClipInset(top float32, right float32, bottom float32, left float32, radius float32) Element
ClipInset clips the element and what is inside it, its background, shadows, border and children, to its box inset by top, right, bottom and left DIPs, with corners rounded by radius, as CSS's clip-path: inset() does. A negative inset reaches beyond the box on that side, as a clip along one axis that leaves a shadow whole along the other. The insets may change every frame, as values an element animates do:
hidden := float32(100)
if app.open {
hidden = 0
}
card.ClipInsetPercent(0, card.AnimateTo("wipe", hidden, ui.Smooth), 0, 0, 0)
What the clip hides takes no clicks.
func (Element) ClipInsetPercent ¶
func (_handle Element) ClipInsetPercent(top float32, right float32, bottom float32, left float32, radius float32) Element
ClipInsetPercent is ClipInset with insets in percent of the box: top and bottom of its height, right and left of its width, as CSS's inset() takes percentages. An inset going from 100 to 0 wipes the element in from the other side.
func (Element) ClipX ¶
ClipX hides what the children draw left and right of the element, and ClipY what they draw above and below it.
func (Element) ColumnCount ¶
ColumnCount tells assistive technology how many columns a table, grid or tree grid of your own has, built or not (aria-colcount).
func (Element) ColumnIndex ¶
ColumnIndex tells assistive technology the place of a cell or a column header among all the columns of its table, grid or tree grid, from 1 (aria-colindex): for one that builds only the columns in view, or leaves some out. Cells without one follow the one before them, after the columns it covers (ColumnSpan).
func (Element) ColumnSpan ¶
ColumnSpan makes the element span n columns of its grid, or, for a negative n, every column from its start to the grid's last, as a header across a grid does. A cell of a table or a grid (RoleCell, RoleColumnHeader, RoleRowHeader) tells assistive technology it covers them, as ARIA's aria-colspan, whether or not its row lays it out in a grid: screen readers read a cell covering two columns as one.
func (Element) ColumnStart ¶
ColumnStart puts the element in column n of its grid, counting from 1.
func (Element) ColumnTracks ¶
ColumnTracks sets the grid's columns, as a sidebar and the rest:
ui.Grid(c).ColumnTracks(ui.Fixed(220), ui.Fr(1))
func (Element) Composing ¶
Composing reports whether an input method composes text in a text input, as Pinyin before a candidate is chosen: its value holds the text once composed. Keys typed meanwhile are the input method's, as Enter choosing a candidate: they submit nothing and press no shortcut.
func (Element) ConicGradient ¶
func (_handle Element) ConicGradient(g ConicGradient) Element
ConicGradient fills the element with a conic gradient, its colors turning around a point (CSS's conic-gradient()):
ui.Box(c).Size(80, 80).Radius(40).ConicGradient(ui.ConicGradient{
Stops: []ui.GradientStop{{red, 0}, {yellow, 1.0 / 3}, {blue, 2.0 / 3}, {red, 1}},
})
func (Element) ContentTransition ¶
func (_handle Element) ContentTransition(t ContentTransition) Element
ContentTransition animates the element's content as it changes, as t says: the text of a Text, the icon of an Icon, the picture of an Image. Changes animate from frame to frame while the element is painted, in frames that only paint. While the desktop asks for less motion, content fades without moving.
ui.Text(c, strconv.Itoa(app.count)).ContentTransition(ui.ContentTransition{Numeric: true, Down: app.decreased})
func (Element) ContextMenu ¶
ContextMenu gives the element a context menu, which build fills with items. The system shows it where the element is clicked with the secondary button, or Control-clicked on macOS, and, while the element or one inside it has the focus, below it when the menu key or Shift+F10 is pressed. build runs when the menu opens, and again in the frame after an item was chosen, where the item's Chosen reports it:
row.ContextMenu(func(m *ui.Menu) {
if m.Item("Rename").Chosen() {
app.renaming = i
}
m.Separator()
if m.Item("Delete").Disabled(app.locked).Chosen() {
app.delete(i)
}
})
The innermost element with a context menu gets the click. Text inputs and selectable text have one with their editing commands, which ContextMenu replaces: on a text input, on a selectable text, or on the Selectable container whose text was clicked. EditItems puts those commands in a menu of one's own:
message.Selectable().ContextMenu(func(m *ui.Menu) {
if m.Item("Reply").Chosen() {
app.reply(msg)
}
m.Separator()
m.EditItems()
})
PopoverMenu draws the same menu in the window, with the theme's look, as ContextMenu does while the window draws its menus (SetMenuPresentation).
func (Element) Controls ¶
Controls tells assistive technology that the element controls the content or the presence of target, as ARIA's aria-controls: the region a disclosure button opens, or the list a filter's input narrows. Screen readers offer to move to it. Call it once target is built, once for each element it controls.
func (Element) CopyData ¶
func (_handle Element) CopyData(fn func(parts []SelectedText) transfer.Data) Element
CopyData sets what Copy, its shortcut and the context menu's put on the clipboard for the selection of a Selectable container: fn gets its parts, as SelectedTexts returns them, and returns the data, as a document copies its paragraphs with blank lines between them as text (transfer.TextData), and as HTML too to keep their formatting.
func (Element) Current ¶
Current tells assistive technology that the element is the current one of the items around it, as the page the user is on in a breadcrumb trail or a navigation bar, which screen readers read with it ("current page"). CurrentNone takes it back.
func (Element) Debug ¶
Debug outlines the element and every element inside it, with their padding and margins, to see the layout.
func (Element) DecorationColor ¶
DecorationColor sets the color of underlines and strikethroughs, which is the text's otherwise.
func (Element) DecorationThickness ¶
DecorationThickness sets the thickness of underlines and strikethroughs in DIPs, which follows the font size otherwise.
func (Element) DescribedBy ¶
DescribedBy has desc, an element the view draws, as a hint below a field or a help text beside it, describe the element to assistive technology, as ARIA's aria-describedby does: screen readers read desc's text after the element's name and value, as a Description, which it follows. The text is desc's Label, else the texts inside it, as a sentence with a link in it, read as one; it counts even when desc is hidden from assistive technology (AccessHidden). Call it once both are built, before or after the element, once for each element describing it, in the order to read them. On a Field, it describes the field's control.
hint := ui.Text(c, "16 digits, no spaces").TextColor(t.TextMuted)
ui.TextInput(c, &app.card).Label("Card number").DescribedBy(hint)
func (Element) Description ¶
Description tells assistive technology more about the element than its name, as help text it reads after it. On a Field, the text shows below the control, and describes it.
func (Element) DimDisabled ¶
DimDisabled sets whether the element shows at half its opacity, with what is inside it, while Disabled disables it, as it does by default, bases too; an element disabled by one around it dims with that one. A widget of your own that shows being disabled in a look of its own, as a card that keeps the reason it is unavailable readable, turns it off and styles itself while IsDisabled.
func (Element) Direction ¶
Direction lays the element and what is inside it out in d, whatever the direction around it: Direction(ui.LeftToRight) keeps a code sample, a phone number or a media player's controls left to right in a right-to-left window, as Flutter's Directionality and SwiftUI's layoutDirection environment do. The elements built inside it inherit it, as do the popups attached to it.
Give it right after creating the element, before its children, logical edges and the parts that read it, as widgets do as they are built: elements already inside take it, and logical edges move to the other side, but what read the old direction keeps it.
func (Element) Disabled ¶
Disabled disables the element and those inside it when d is true: they report no clicks, take no focus, and show at half their opacity, unless DimDisabled turns that off. AccessDisabled keeps their clicks and their focus, for what assistive technology must still reach.
func (Element) Dismissed ¶
Dismissed reports whether pressing Escape or clicking outside closed the dialog or popover (Modal, DialogBase, Popover, PopoverBase) returning the element, in the frame it did, setting its *open to false: one that must stay open sets it back to true.
if ui.Modal(c, &app.editing, edit).Dismissed() && app.unsaved {
app.editing = true
}
func (Element) Dividers ¶
Dividers draws a line width DIPs thick in color c between each two children of a row, a column or a List (between their rows), across the element, inside its border: in the middle of the room between them, which the lines do not take, so give the element a Gap at least as wide. A row that wraps draws them between the children of each line; grids draw none.
func (Element) DottedUnderline ¶
DottedUnderline underlines text with a line of dots, as links mark hover.
func (Element) DoubleClicked ¶
DoubleClicked reports a double click on the element.
func (Element) Drag ¶
Drag makes the element the source of value, dragged within the window once the pointer pressing the element moves a few DIPs: a copy of the element follows the pointer, and the element taking the value under it gets it when the pointer is released (Drop). A press dragging is no click. Dragging reports the drag.
func (Element) DragData ¶
DragData makes e a native drag source after a primary press moves a few DIPs. Data can go to other windows and applications. A source also given Drag(value) offers that value to typed targets in this process only. The default operation is copy and the default preview is the element.
func (Element) DragDataFrom ¶
func (_handle Element) DragDataFrom(data func() transfer.Data, options ...transfer.DragOptions) Element
DragDataFrom obtains a transfer when the gesture starts, useful for a changing selection. The function and options.Done run on the main thread. See transfer.Lazy for deferring individual serialized representations.
func (Element) DragEnded ¶
DragEnded reports whether the pointer pressing the element with the primary button, and moving, let go since the last frame, with how fast it moved then, as DragVelocity: a spring taking over (SpringOptions.Velocity) keeps the fling going. A click, which does not move, ends no drag, nor does a drag with another button, nor a press the system canceled (PressCanceled).
func (Element) DragMissed ¶
DragMissed reports, in the frame after, that the value the element drags (Drag) was let go over no element taking it, and where, in the window's coordinates: outside the window when it was let go past its edge, as to tear a tab out into a window of its own. A drag given up, with Escape, is not missed.
func (Element) DragOffset ¶
DragOffset returns where Draggable shows the element in this frame, from its place in the layout: following the pointer, or on its way to rest. Reading it builds the view in every frame the element moves in, as AnimateTo does, which the element otherwise moves in without: for what follows the element, as a backdrop fading as a sheet goes down. Call it after Draggable.
func (Element) DragVelocity ¶
DragVelocity returns how fast, in DIPs per second along the element's local axes, the pointer pressing the element moves now: zero once it stops for a moment, or while nothing presses the element with the primary button (Dragged).
func (Element) DragWindow ¶
DragWindow makes the element a handle that moves the window, such as the title bar of a frameless window. A double click on it maximizes the window, as on a title bar.
func (Element) Draggable ¶
func (_handle Element) Draggable(offset *Point, o DraggableOptions) Element
Draggable lets the pointer move the element from its place in the layout, by *offset, and returns the element. As the pointer drags it, the element follows the pointer, along its parent's axes, and *offset with it; once the pointer lets go, *offset is where the element comes to rest, as o says, and it goes there. Setting *offset moves the element there as well, as o.Animation says. A nil offset is kept in the element.
The element moves after its own transform (Transform) and its pose (AnimatePose), and goes to rest in frames that only paint, without building the view, as AnimatePose moves it. Dragging reports that the pointer drags it, once the pointer moved a few DIPs, Transitioning that it moves, and DragOffset where it shows. A press dragging it is no click; a press catches it as it moves. A press the system cancels (PressCanceled) throws nothing, and the element goes back to where the press took it. While the desktop asks for less motion (Preferences.ReduceMotion), it goes to rest at once.
sheet.Draggable(&app.sheet, ui.DraggableOptions{
Axis: ui.Vertical,
Bounds: &ui.Rect{H: 400},
Snap: ui.Nearest(ui.Point{}, ui.Point{Y: 200}, ui.Point{Y: 400}),
})
func (Element) Dragged ¶
Dragged reports how far the pointer moved in the element's local axes since the last frame while pressing it with the primary button, as Pressed: a drag with another button moves nothing (PressedButton). The moves just before the pointer let go come while the element is still pressed, and the press ends in the build after.
func (Element) Dragging ¶
Dragging reports whether the element is dragging its value (Drag), or the pointer is dragging the element (Draggable).
func (Element) Draw ¶
Draw paints on the element with p after its background, before its children; r is its box. fn only paints: it may run more than once a frame.
func (Element) DrawObjects ¶
DrawObjects paints the inline objects of a text (Span.ObjectWidth) with p, after its glyphs: fn gets each one that shows, its rune in the text, the text elements' inside it included, and its box, in window DIPs, ObjectHeight above the baseline and ObjectDescent below. It paints in the text's clip and in the transform of the element holding the object. fn only paints: it may run more than once a frame.
ui.RichText(c, ui.Span{Text: "area "}, ui.Span{Text: "\uFFFC", ObjectWidth: w, ObjectHeight: h, ObjectDescent: d}).
DrawObjects(func(p *ui.Painter, at int, r ui.Rect) { formula.Draw(p, r) })
func (Element) DroppedFiles ¶
DroppedFiles returns the paths of the files dropped on the element since the last frame, nil when none, and makes the element take files dragged over it.
func (Element) Effect ¶
Effect draws the element, with its children, through fx, an effect of package ui/shader, in place of drawing it as it is; nil draws it as it is:
ui.Text(c, "Wavy").Effect(wave.Effect(shader.Options{
Uniforms: map[string]any{"Time": t},
MaxSampleOffset: ui.Point{Y: 8},
}))
What the element renders, with its children, shadows and what its Draw callbacks paint, renders into a bitmap of the GPU, the size of its box and the effect's margin (Effect.EffectMargin) around it, every frame the element paints, which the effect then draws over the box and the margin, transformed, clipped and faded as the element would be. Web views inside the element do not show through an effect.
func (Element) Ellipsis ¶
Ellipsis sets what ends text that MaxLines or SingleLine cuts, "…" by default.
func (Element) EndPercent ¶
func (Element) Error ¶
Error marks the element's value as not valid, for msg, which assistive technology reads with it; an empty msg leaves it valid. On a Field, the message shows below the control in the theme's Danger color, and marks the control, whose border text inputs draw in that color.
func (Element) ErrorMessage ¶
ErrorMessage has msg, an element the view draws holding the message of the element's error, tell assistive technology why its value is not valid, as ARIA's aria-errormessage does: while the element is invalid (Invalid, Error), screen readers read msg's text with it, first in its description, and those that follow the relation go to msg. While it is valid, msg says nothing of it, so the view may keep msg built, empty or hidden. Call it once both are built, once for each element holding a message. On a Field, it is the field's control's message.
in := ui.TextInput(c, &app.email).Label("Email").Invalid(app.emailError != "")
if app.emailError != "" {
in.ErrorMessage(ui.Text(c, app.emailError).TextColor(t.Danger))
}
func (Element) Expanded ¶
Expanded tells assistive technology whether what the element opens shows, as the popup of a button or the section below a header.
func (Element) FileDragOver ¶
FileDragOver reports whether files dragged from another app are over the element, which takes them if they are dropped, for showing it would.
func (Element) FillHeight ¶
FillHeight makes the element as tall as its parent's content.
func (Element) FixedLineHeight ¶
FixedLineHeight sets the height of lines of text in DIPs, whatever the font size, as for rows of text that line up with a grid.
func (Element) Focus ¶
Focus gives the element the keyboard focus. Called in every frame, it keeps it there; AutoFocus gives it once. A field around an input, as SearchField's, gives it to its input, where typing goes.
func (Element) FocusBind ¶
FocusBind binds desired focus to a comparable value in an app-owned field. Assign another value to request that control; its request waits while hidden. User focus changes update the field when no request is waiting. The field holds desired focus: use FocusedValue to read actual focus while a request waits. Each window should use its own field. Values must be unique per field.
func (Element) FocusGroup ¶
func (_handle Element) FocusGroup(o Orientation) Element
FocusGroup makes the elements inside the element that take the focus one stop of Tab, as the controls of a toolbar, a radio group or a tab list are: Tab moves the focus into the group, to the element of it that had it last (else the radio button or tab chosen, else the first; in a radio group or a tab list, the one chosen first), and on out of it; the arrows that o names move it among them, round from the last to the first, and Home and End to the first and the last. An element inside that takes those keys itself, as a slider or a text input does, keeps them. Groups inside a group are part of it.
func (Element) FocusLeft ¶
FocusLeft reports whether the keyboard focus left the element since the last frame: it was on the element or inside it, and is now outside it, or nowhere, as the window lost the keyboard. That is the web's focusout whose relatedTarget the element does not contain. The overlays attached to the element and to those inside it (AttachTo), as a combobox's list or a button's popover, count as inside it, as does the element it is attached to, as PressedOutside has them: a combobox closes as the focus leaves its field, but not as it moves into its list.
field := ui.TextInput(c, &app.query)
if field.FocusLeft() {
app.open = false
}
Where the focus went is what the elements tell as they are built (Focused, FocusWithin), and a Handle's FocusWithin before its control is.
func (Element) FocusRing ¶
FocusRing sets whether MyGo rings the element when it has the keyboard focus from the keyboard, as it does by default. Widgets that ring a part of themselves instead, as a check box its box, turn it off and draw their own with Painter.FocusRing while FocusVisible.
func (Element) FocusRingColor ¶
FocusRingColor sets the color of the element's focus ring, in place of the theme's Focus, as for an element on a background the theme's ring does not stand out on.
func (Element) FocusRingOffset ¶
FocusRingOffset sets how far outside the element's edge its focus ring goes, in DIPs, in place of the theme's FocusRingOffset: 0 puts it on the edge, and a negative offset inside it, as for an element whose ancestor clips what goes past it, as a header in an accordion's box. Its corners follow the element's, as CSS's outline does. The widgets that ring a part of themselves, as a check box its box, ring it so.
func (Element) FocusVisible ¶
FocusVisible reports whether the element has the keyboard focus and should show it, because it came from the keyboard.
func (Element) FocusWithin ¶
FocusWithin reports whether the element or one of its descendants has the keyboard focus.
func (Element) Focused ¶
Focused reports whether the element has the keyboard focus: for a field around an input, as SearchField's, whether its input has it.
func (Element) Font ¶
Font sets the font family, a comma-separated list: the first family the system or the app has draws the text, and the others, in order, what it lacks, before the system's choice. "monospace" and "system-ui" are the system's own fonts.
func (Element) FontFeatures ¶
FontFeatures turns on OpenType features of the font, by tag, or sets them with tag=value:
ui.Textf(c, "%d items", n).FontFeatures("tnum") // digits of one width
ui.Text(c, "office").FontFeatures("liga=0") // no ligatures
A font without a feature ignores it.
func (Element) FontSize ¶
FontSize sets the size of text in DIPs, for the element's text and its descendants'.
func (Element) FontWeight ¶
FontWeight sets the weight of text from 100 (thin) to 900 (black).
func (Element) Gap ¶
Gap puts space between children, and between the lines of a wrapping container or the tracks of a grid.
func (Element) Gradient ¶
Gradient fills the element with a linear gradient from one color to another, at angle degrees clockwise from upwards as in CSS: 180 goes from top to bottom, 90 from left to right.
func (Element) Grow ¶
Grow gives the element a share f of the free space along its parent's main axis: Grow(1) on one child makes it take all of it. Like CSS flex: f, the element then starts from no size (unless Basis says otherwise) and may shrink below its content in a column, which suits a list or editor filling the rest of a window.
func (Element) HandleInput ¶
func (_handle Element) HandleInput(fn func(ev InputEvent) bool) Element
HandleInput has fn take the element's input as it comes, on the main thread, before the next frame is built: keys, text and edit commands while the element has the keyboard focus, the pointer pressed on it, moving over it, scrolling or pinching over it. fn reports whether it took the event; one it leaves goes on as it would without fn, to shortcuts, Tab, context menus and scroll containers. Keys that the window or an element around the focus handles as a Shortcut go to the shortcut first. A frame follows the events fn takes.
It is for widgets that need every key as it is pressed, such as a terminal, or the scrolling and pinching over them, such as a chart that zooms and pans; most widgets ask about their input as they are built instead (Clicked, Shortcut, Dragged).
func (Element) HandleTextInput ¶
func (_handle Element) HandleTextInput(client TextInputClient) Element
HandleTextInput connects an element to the system's text-input services. Pair it with HandleInput for keys, pointer selection and Edit-menu commands, and Draw for rendering. It adds focus and the text cursor without creating a text buffer, formatting UI or undo history. A nil client disconnects it. Existing TextInput/TextArea widgets and TextCaret handlers are unchanged.
func (Element) HasPopup ¶
HasPopup tells assistive technology the kind of popup the element opens, as a button opening a list of options (PopupListBox) or a menu (PopupMenu), which Expanded says shows: screen readers read it with the element ("pop-up button", "menu button") and offer to open it. PopupNone takes it back. Menu buttons (Menu, PopoverMenuButton, MenuButton, MenuBase) tell PopupMenu themselves; HasPopup, before or after, wins over it.
func (Element) HeightPercent ¶
HeightPercent sets the height as a percentage of the parent's.
func (Element) Hidden ¶
Hidden hides the element and its children when hide is true, as CSS's display: none does: unlike an Invisible element, it takes no room in the layout, nor a gap between its siblings, and draws nothing, takes neither the pointer nor the focus, and is not read by assistive technology. It is still built, so that what is inside it keeps its state (scroll offsets, text being edited, animations) while it is hidden, and shows as it was once hide is false again:
ui.Column(c).Hidden(!app.showDetails).Children(func() { ... })
The focus leaves it as it hides, and what is attached to it (AttachTo) hides with it. A List's rows are built as the list lays out, so a hidden List builds none.
func (Element) Highlighted ¶
Highlighted reports whether an option of a select, or an item of a menu (MenuBase), is the one the pointer or the arrows are on.
func (Element) HitTest ¶
HitTest sets where in its box the element takes the pointer: where fn reports true for the pointer at (x, y), in the coordinates Draw paints in, r being its box as Draw gets it. Elsewhere the pointer reaches what is under it, as with PassThrough, so that a pie's segment, a map's region or a ring takes a press, the hover and the cursor only where it paints, as SVG's pointer-events: visiblePainted. The elements inside it take the pointer as they would; fn runs as the pointer moves and presses, on the window's thread, and only tests:
ring := func(r ui.Rect) *ui.Path {
var p ui.Path
cx, cy := r.X+r.W/2, r.Y+r.H/2
return p.Circle(cx, cy, r.W/2).Circle(cx, cy, r.W/2-12).FillRule(ui.EvenOdd)
}
ui.Box(c).Size(120, 120).
Draw(func(p *ui.Painter, r ui.Rect) { p.FillPath(ring(r), accent) }).
HitTest(func(x, y float32, r ui.Rect) bool { return ring(r).Contains(x, y) }).
OnClick(func() { … })
func (Element) HostLayer ¶
func (_handle Element) HostLayer(layer *UILayer, surface SurfaceMap) Element
HostLayer makes e the native host of layer's text input, cursor and accessibility tree through surface. It does not route pointer input or render the layer: use layer.HandleSurfaceInput in e's HandleInput and render when layer.NeedsFrame reports true.
The merged accessibility nodes carry layer-relative bounds projected through surface and then through e's layout and visual transforms. Assistive-technology actions route back to the layer's own engine.
func (Element) Hovered ¶
Hovered reports whether the pointer is over the element. While the pointer presses an element, the elements it was over as the press began, as those around the element pressed, stay hovered as long as it is over them, as in CSS, and the others hover no more: a button that shows over a row stays as it is pressed, and dragging over other elements does not light them up.
func (Element) IgnoreInput ¶
IgnoreInput makes the element and those inside it ignore the pointer and the keyboard when ignore is true, while they still show and read to assistive technology. The pointer goes through to what is under them, as PassThrough lets it: hovering, pressing, scrolling, dragging and the cursor are those of what is under them. Neither Tab nor a click gives them the focus, and they lose it as they start ignoring input. Assistive technology still finds them, with their roles and names, and presses them, which Clicked reports; it can neither focus them nor move a slider among them with its keys. A WebView inside them still takes the pointer, which the system gives its view.
A control a row shows while it is hovered, as a button deleting it, can stay built and described at rest, without taking a press meant for the row:
row := ui.Row(c).Padding(8)
hovered := row.Hovered()
row.Children(func() {
ui.Text(c, item.Title).Grow(1)
del := ui.Button(c, "Delete").IgnoreInput(!hovered)
if !hovered {
del.Opacity(0)
}
if del.Clicked() {
removed = item.ID
}
})
Unlike HTML's inert, it leaves them to assistive technology. Invisible and Hidden hide them from it too, and Disabled takes their press away; AccessHidden hides them from it alone.
func (Element) InView ¶
InView reports whether some of the element showed in the window in the frame before, within the scroll containers and clips around it: to animate it in as it scrolls into view, as Motion's whileInView.
func (Element) InViewAmount ¶
InViewAmount reports whether at least amount of the element's area, from 0 to 1, showed in the frame before, within the window and the scroll containers and clips around it, grown by margin as InViewMargin grows them: as IntersectionObserver's threshold, and Motion's amount for whileInView and useInView. An impression counts once half of a card shows with 0.5, an animation starts at a fifth of it with 0.2, and 1 waits for all of it; 0 is InViewMargin. Its area is that of its box as transforms move it, the box holding them as InView's clips do.
card := ui.Column(c).Key(ad.ID)
if card.InViewAmount(0.5) {
app.counted(ad.ID)
}
func (Element) InViewMargin ¶
InViewMargin reports whether some of the element showed in the frame before, as InView does, with the window and the scroll containers around it grown by margin, in DIPs, CSS style as Padding: all sides, vertical and horizontal, or top, right, bottom and left. As IntersectionObserver's rootMargin and scrollMargin, a margin of 200 has the element in view once it is within 200 DIPs of showing, to load what it shows before it scrolls in, and a negative one only once it is that far inside; other clips around it clip it as they do.
func (Element) InputMethod ¶
InputMethod sets whether the system's input methods compose text for the element while it has the keyboard focus, as they do by default for one that takes text (HandleTextInput, TextCaret). Turned off, keys type the characters of the keyboard's layout, which come as InputText, and nothing is composed: a mode that reads letters as commands, as Vim's normal mode, gets j as j with a Chinese input method on, as Neovide and winit's set_ime_allowed(false) have it. Browsers cannot turn input methods off, and compose still.
func (Element) InsetShadow ¶
func (_handle Element) InsetShadow(x float32, y float32, blur float32, spread float32, c Color) Element
InsetShadow adds an inner box shadow, as CSS's box-shadow: inset: offset by x and y, blurred by blur and grown inward by spread DIPs. It shows only inside the box's padding edge, within its border and rounded corners, above the background and below the content. Inner shadows stack in the order they are added, as outer ones do.
func (Element) Invalid ¶
Invalid marks the element's value as not valid, as ARIA's aria-invalid, without a message: assistive technology reads the element as invalid, and a text input draws its border in the theme's Danger color, but its description stays as it is. It suits a required field marked as the user leaves it empty, whose message waits for the form to be submitted, or a control whose message is an element of its own (ErrorMessage). On a Field, it marks the field's control. false leaves the element as it is: valid, unless Error, or the control's own check of what is typed into it, marks it.
ui.TextInput(c, &app.card).Label("Card number").
Invalid(app.cardTouched && app.card == "")
func (Element) Invisible ¶
Invisible hides the element and its children, which keep their room in the layout but draw nothing and take neither the pointer nor the focus, as CSS's visibility: hidden does. Hidden takes the room away too.
func (Element) IsDisabled ¶
IsDisabled reports whether the element or an ancestor is disabled.
func (Element) Jump ¶
Jump sets the value animated under key to value at once, as a drag moves it under the pointer, and returns it. The value's velocity follows the jumps from frame to frame, so that a spring taking over from the last (AnimateTo) keeps going the way it went.
func (Element) JustifyItems ¶
JustifyItems places the children of a grid in their cells horizontally: Stretch (the default), Start, Center or End. AlignItems places them vertically.
func (Element) JustifySelf ¶
JustifySelf places the element in its grid cell horizontally, overriding its grid's JustifyItems.
func (Element) KeepFocus ¶
KeepFocus leaves the keyboard focus where it is while the element, or what is inside it, is pressed: the popups and bars of a control that keeps typing while the user picks in them, as a combobox's options or a code editor's completions and find buttons.
func (Element) KeepOpen ¶
KeepOpen keeps a menu open as its item is chosen (MenuBase, ContextMenuBase): by the pointer, Enter or Space, the item reports Clicked and stays highlighted, as a check box item flipping a setting one may flip again, or a radio item of a Group switching the theme while the menu shows it.
func (Element) KeepScrollbars ¶
KeepScrollbars keeps this scroll container's scroll bars showing while its content overflows it, with the pointer over it or not, rather than only while it is hovered or a bar is dragged: a view whose place in its content matters, as a long diff filling a window, shows how far down it is. The bars look and take presses as they do on hover; Scrollbars(false) hides them still. It applies where Scrollbars does (a code editor's State has KeepScrollbars), and is not inherited.
func (Element) Key ¶
Key keys a container before its children or local state are built. For a stateful control, use Context.Key before construction instead.
func (Element) KeyShortcuts ¶
KeyShortcuts tells assistive technology a key, with exactly the modifiers mods, that presses or focuses the element, as ARIA's aria-keyshortcuts: the window's shortcut that runs a toolbar button's command, or opens a command palette, which screen readers read with the element's name. It is written as the platform's menus write it ("⌘K" for Cmd+K on macOS, "Ctrl+K" elsewhere). It only tells the key: handle it with Shortcut on the context, or OnWindowShortcut. Call it once for each key that does.
func (Element) Keyframes ¶
func (_handle Element) Keyframes(key any, frames []Keyframe, options ...KeyframeOptions) float32
Keyframes plays a sequence, holding its last value when done. It starts on the first call, with the first frame's value. Keep the element and key stable, and change Run when changing the sequence. Only active playback asks for animation frames. Reduced motion completes playback at its final value, including when the preference changes mid-sequence, unless the options' NonMotion says the sequence moves nothing.
func (Element) Label ¶
Label names the element for assistive technology and for finding it in tests, when its text does not.
func (Element) LabelledBy ¶
LabelledBy has label, a text the view draws as the element's caption, name the element for assistive technology, in place of its Label or the text inside it, as ARIA's aria-labelledby does, and gives a click on label to the element, as HTML's <label for> does: the click focuses it, as a text input, or in a group of controls, as a RadioGroup, the one chosen, else the first, and clicks a check box, a switch or a radio button, as a Field's label does. Call it once both are built, before or after the element:
label := ui.Text(c, "Card number").TextColor(t.TextMuted) ui.TextInput(c, &app.card).LabelledBy(label)
A label that is no text names the element by its Label.
func (Element) Lang ¶
Lang sets the language of the element's text, and of the text of the elements inside it, as a BCP 47 tag, as HTML's lang attribute does: the system's text stack draws the glyphs of that language, as the Han characters Chinese and Japanese draw apart, and falls back to its fonts. Text is in the language the app shows (mygo.App.Locale) unless told otherwise: a Japanese quote in a Chinese app,
ui.Text(c, "直").Lang("ja")
Korean text ("ko", "ko-KR") breaks its lines between words, at spaces and after punctuation, as Korean is written and as CSS's word-break: keep-all has it, rather than between any two syllables; a word longer than a line still breaks within it. "" takes the language of the elements around it. Browsers draw text in the page's language whatever the element's.
func (Element) LayoutBounds ¶
LayoutBounds returns the previous frame's border box before transforms, in the layout's window coordinates. Draw callbacks use these coordinates.
func (Element) LeftPercent ¶
func (Element) LetterSpacing ¶
LetterSpacing adds v DIPs after every character of text, or tightens it with a negative v, as for labels in capitals; 0 takes away that of the text around it, as for a number within such a label.
func (Element) Level ¶
Level tells assistive technology the rank of a heading, from 1 for the highest, or how deep an item of a tree is, from 1 at the top.
func (Element) LineHeight ¶
LineHeight sets the height of lines of text as a multiple of the font size.
func (Element) LinearGradient ¶
func (_handle Element) LinearGradient(g LinearGradient) Element
LinearGradient fills the element with a gradient, of which Gradient sets only the colors and the angle.
func (Element) Lines ¶
Lines makes a text area as high as its text, wrapped at its width, from min lines up to max, past which it scrolls, as a message field grows with what is typed: TextArea(c, &draft).Lines(1, 8). Without it, a text area is as high as its paragraphs, three lines at least, unless given a height.
func (Element) LocalToWindow ¶
LocalToWindow maps a point in the previous frame's border box to the window.
func (Element) Loop ¶
Loop returns the progress of an animation that starts over every period, from 0 to 1 along ease, and keeps frames coming while the element is built; key tells apart the animations of the element. A spinner turns with Loop("spin", time.Second, ui.Linear) * 360, and a placeholder pulses with an opacity of 0.5 + 0.5*Loop("pulse", d, ui.Bounce(ui.EaseInOut)).
func (Element) Margin ¶
Margin sets the space around the element, as Padding does. Auto margins take the free space on their side.
func (Element) MarginStart ¶
MarginStart and MarginEnd set the margin on the side lines start and on the other, as PaddingStart does: Auto takes the free space there, so that a Row's child with MarginStart(ui.Auto) goes to its end.
func (Element) MaskConicGradient ¶
func (_handle Element) MaskConicGradient(g ConicGradient) Element
MaskConicGradient masks the element and what is inside it by a conic gradient, as MaskLinearGradient does by a linear one: a ring revealed as its stops turn.
func (Element) MaskLinearGradient ¶
func (_handle Element) MaskLinearGradient(g LinearGradient) Element
MaskLinearGradient masks the element and what is inside it by a linear gradient across its box, as CSS's mask-image: linear-gradient() does: each point shows as much as the gradient's alpha there, whatever its colors, and nothing shows outside the box (or the inset of ClipInset). A list whose rows fade out at its top and bottom edges:
black := ui.RGB(0, 0, 0)
fade := []ui.GradientStop{{ui.Transparent, 0}, {black, 0.1}, {black, 0.9}, {ui.Transparent, 1}}
list.MaskLinearGradient(ui.LinearGradient{Angle: 180, Stops: fade})
Each thing drawn is masked on its own, rather than the element drawn into a layer first, as Opacity fades a group: where the mask lets a part through, a row's background shows what is under it too.
func (Element) MaskRadialGradient ¶
func (_handle Element) MaskRadialGradient(g RadialGradient) Element
MaskRadialGradient masks the element and what is inside it by a radial gradient, as MaskLinearGradient does by a linear one: a vignette, or a spotlight.
func (Element) Masks ¶
Masks masks the element and what is inside it by layers of masks, the first on top, each composited with those after it as its Composite says, as CSS's mask-image with mask-composite does: each point shows as much as the result's alpha there, and nothing shows outside the box (or the inset of ClipInset). It replaces MaskLinearGradient and the others, which make one layer, and they replace it. A ring 1.5 DIPs wide, of a gradient, its middle cut out by a layer over the content box:
black := ui.RGB(0, 0, 0)
solid := ui.LinearGradient{From: black, To: black}
ui.Box(c).Size(120, 40).Radius(20).Padding(1.5).Gradient(pink, violet, 90).Masks(
ui.Mask{Image: solid, Box: ui.MaskContentBox, Composite: ui.MaskExclude},
ui.Mask{Image: solid},
)
and a crescent, a disc less one beside it:
disc := func(x, y float32) ui.RadialGradient {
return ui.RadialGradient{Center: ui.Point{X: x, Y: y}, Radius: 40,
Stops: []ui.GradientStop{{black, 0.98}, {ui.Transparent, 1}}}
}
moon.Masks(ui.Mask{Image: disc(0.5, 0.5), Composite: ui.MaskSubtract}, ui.Mask{Image: disc(0.7, 0.35)})
Layers that are not one gradient across the border box make a mask of their alpha, drawn once for each size the element paints at.
func (Element) MaxHeightPercent ¶
func (Element) MaxLength ¶
MaxLength keeps the user from making a text input's value longer than n, counted as HTML's maxlength counts it, in UTF-16 code units, a newline as one: text typed, pasted or committed by an input method is cut to what fits at the caret, and replacing a selection takes what fits in its place. A value the app sets is not cut. n <= 0 means no limit. Like ReadOnly, it holds for the input that comes until the next frame.
func (Element) MaxLines ¶
MaxLines shows at most n lines of the element's text, ending it with an ellipsis.
func (Element) MaxWidthPercent ¶
func (Element) MaximizeButton ¶
MaximizeButton marks the element as the window's maximize button, which the view draws in a window with a hidden title bar without the system's (mygo.WindowOptions.HideWindowButtons): on Windows 11, holding the pointer over it shows the snap layouts, as over the system's. It takes the pointer as any element does, and the view maximizes the window when it is clicked (mygo.Window.Maximize). The first such element of a frame counts; elsewhere it does nothing.
func (Element) Menu ¶
Menu makes the element a menu button: it opens a menu below it, which build fills with items, as the pointer goes down on it, as a pop-up button does, and for Enter, Space or Down while it has the focus. It takes the focus. build runs when the menu opens, and again in the frame after an item was chosen, where the item's Chosen reports it, as for ContextMenu. MenuButton is a button with a menu:
more := ui.ButtonBase(c).Label("More").Padding(4).Radius(6)
more.Children(func() { ui.Icon(c, moreIcon).Size(16, 16) })
more.Menu(func(m *ui.Menu) {
if m.Item("Duplicate").Chosen() {
app.duplicate()
}
})
PopoverMenuButton draws the same menu in the window, with the theme's look, as Menu does while the window draws its menus (SetMenuPresentation).
func (Element) MinHeightPercent ¶
func (Element) MinWidthPercent ¶
MinWidthPercent, MinHeightPercent, MaxWidthPercent and MaxHeightPercent bound the size by a percentage of the parent's. With a bound in DIPs too, both apply: the larger minimum and the smaller maximum, as CSS's max-width: min(78%, 34rem) for a chat bubble:
ui.Box(c).MaxWidthPercent(78).MaxWidth(544)
func (Element) Mixed ¶
Mixed tells assistive technology that the element, a check box, is partly on, as one checking a group whose boxes differ.
func (Element) Modal ¶
Modal makes the element, built in an Overlay, a dialog's backdrop, as DialogBase's: while it shows, the focus moves into it, Tab goes round the elements inside it, the window's shortcuts built outside it wait, and assistive technology sees it and what shows above it alone, as what is behind it is inert. Build the dialog inside it.
func (Element) Multiselectable ¶
Multiselectable tells assistive technology whether the user chooses several of the items of the element, a list, grid, tree or tree grid of your own, as ARIA's aria-multiselectable: screen readers offer to choose more than one. Its rows or items say which are chosen with Checked, or Selected, which shows it too. Lists, tables and grid views with a Selection tell it themselves.
func (Element) NoShadow ¶
NoShadow takes off the outer and inner shadows added so far, as CSS's box-shadow: none, so that the Shadow and InsetShadow calls after it start afresh.
func (Element) NoWrap ¶
NoWrap keeps each line of the element's text whole, breaking it only at newlines, even where it overflows the element.
func (Element) ObjectPosition ¶
ObjectPosition places an Image's picture in its box where Fit leaves room around it, or crops it, as CSS's object-position: x and y are fractions of that room across and down, 0 by the left or top edge, 1 by the right or bottom one, and 0.5, as by default, in the middle. An avatar's face, near the top of its photo, stays in view with
ui.Image(c, photo).Size(40, 40).Fit(ui.Cover).ObjectPosition(0.5, 0.15)
as object-position: 50% 15%; the edge keywords are 0 and 1, as ObjectPosition(1, 0) for right top. Values beyond 0 and 1 move the picture further, past the box's edges.
func (Element) ObserveInput ¶
func (_handle Element) ObserveInput(fn func(ev InputEvent)) Element
ObserveInput has fn see the input that comes to the element or to an element inside it, without taking it, as an ancestor listening to the keydown events that bubble up to it from the focus: keys pressed and released (with Repeat), text typed and composed, and the edit commands of the menus while the element or one of its descendants has the keyboard focus, and the pointer pressed and released over it. fn runs on the main thread before the element the input goes to gets it (the capture phase of UI Events), the outermost of the elements observing first, with X and Y relative to its own box; the input then goes on as it would without fn, to HandleInput, the text inputs, shortcuts, Tab and the rest, which may move the focus. A frame follows the input fn sees.
fn sees what HandleInput would see at the focus, whatever takes it, keys a Shortcut takes and Tab among them, but not the keys the system or the menus take before the window gets them (an edit command of the menus comes instead, InputCommand), the keys a web view takes while it has the focus, nor the input of the popovers, menus and dialogs the element opens, which are not inside it. A key that moved the focus, as Tab, comes up where the focus went, as with UI Events. A disabled element observes nothing.
It is for a region that reacts to any input in it, such as a demo that stops playing at the first key pressed in it, or a panel that closes a hint as soon as one of its fields is typed in.
func (Element) OnChange ¶
OnChange runs after input changes the bound value, before rebuilding the view. The callback can commit a derived value local to this build pass.
func (Element) OnPaste ¶
OnPaste has fn see a paste into a text input, by Cmd+V, Ctrl+V or a Paste menu item, before it is inserted, on the main thread as the paste comes: text is the clipboard's text, empty when it holds none, as with an image, which the app reads from the clipboard itself. fn reports whether it took the paste; a paste taken changes nothing, its selection and undo history included, as when a web page prevents a paste's default and attaches a large block instead of inserting it. Like ReadOnly, it holds for the input that comes until the next frame.
func (Element) OnShortcut ¶
OnShortcut declares a key handler within the element's focus subtree.
func (Element) OnSubmit ¶
OnSubmit runs after bound-value input handles a submission gesture, before rebuilding the view.
func (Element) OnTextKey ¶
OnTextKey has fn see a key pressed in the text input before the input takes it, on the main thread as the key comes, with the text typed before it in place, as AppKit's doCommandBySelector and a web page's keydown on a text field: Enter that sends a message, Up that edits the last one, Tab that accepts a completion, Escape that cancels, Cmd+Enter. fn reports whether it took the key; one taken changes nothing but what fn sets: a text area inserts no newline, a single-line input does not submit, Tab does not move the focus. One left goes on as it would without fn.
fn sees the keys that type no text: those with Cmd or Ctrl, and Enter, Tab, Escape, Backspace, Delete, the arrows and the other keys that move the caret, as pressed (macOS's Control keys that move the caret too). While an input method composes, its keys are its own. Keys that the window or an element around the focus handles as a Shortcut go to the shortcut first, as with HandleInput, unless the input edits with them, as with Enter and the arrows. Like ReadOnly, OnTextKey holds for the input that comes until the next frame.
fn runs between frames, where an Element kept from the view is no longer valid: it reads and replaces the text through k instead, as a chat composer sends with Enter, clears what it sent, and breaks the line with Shift+Enter:
ui.TextArea(c, &app.draft).OnTextKey(func(k ui.TextKey) bool {
if k.Key != ui.KeyEnter || k.Mods != 0 {
return false // Shift+Enter breaks the line
}
app.send(k.Text())
k.SetText("")
return true
})
func (Element) Opacity ¶
Opacity makes the element and its children translucent as one group, as CSS's opacity does: what they paint is composited first and then faded, so that children overlapping one another, or the element's background under them, never show through each other. Where nothing they paint overlaps, they paint faded each on its own, which looks the same and costs nothing more; otherwise they render into a layer of the GPU first, in which text is smoothed in grayscale, as in Cache's. A web view or a material reading its backdrop inside the element shows through no layer: there each thing fades on its own. Disabled's dimming fades each thing on its own too.
func (Element) Orientation ¶
func (_handle Element) Orientation(o Orientation) Element
Orientation tells assistive technology which way the element runs, as ARIA's aria-orientation: Vertical for a slider, separator, splitter, toolbar, tab list or menu of your own going up and down, which screen readers then read as vertical, Horizontal for one going across. It only tells it: the view lays the element out and handles its keys itself (FocusGroup). A slider or a separator told neither runs across, a separator taller than wide up and down; other elements have no orientation. A SliderBase going up says so itself (Vertical).
ui.Box(c).Size(4, 200).Draw(drawTrack).
Role(ui.RoleSlider).Label("Volume").Range(0, 100, app.volume).
Focusable().Orientation(ui.Vertical)
Any other value, as Horizontal|Vertical, takes it back.
func (Element) OverlayShortcut ¶
OverlayShortcut reports whether the key with exactly the modifiers mods was pressed for the element, an overlay, which gets the keys the focused element and those around it leave, wherever the focus is: the overlay built last first, so that Escape closes the one on top. Overlays close with it, as PopoverBase and DialogBase do:
if panel.OverlayShortcut(0, ui.KeyEscape) {
app.open = false
}
func (Element) Padding ¶
Padding sets the space inside the element's edges, CSS style: all sides, vertical and horizontal, or top, right, bottom and left.
func (Element) PaddingEnd ¶
func (Element) PaddingStart ¶
PaddingStart sets the padding on the side lines start: the left, or the right of an element laid out right to left, as CSS's padding-inline-start does. PaddingEnd sets the other side's.
func (Element) PassThrough ¶
PassThrough lets the pointer reach what is under the element.
func (Element) Password ¶
Password hides what a text input holds, in the frames that call it: an input that stops calling it shows its text again, as a field's eye button does. It does nothing to a text area: as on every platform, only single-line fields hide their text.
func (Element) Perspective ¶
Perspective sees the element's transform in 3D from distance DIPs in front of its origin (Perspective).
func (Element) Placeholder ¶
Placeholder shows s in an empty text input. On a field around an input, as SearchField, TokenField and Combobox, it shows in the field's input, in place of the field's own: SearchField shows Search without one.
func (Element) PlaceholderColor ¶
PlaceholderColor sets the color of this input's placeholder for this build. When unset it uses the theme's TextMuted. It does not change entered text, other inputs or the theme. A transparent color hides the placeholder.
func (Element) PointerPosition ¶
PointerPosition returns the pointer's position relative to the element's box and whether it is over the element. Elements asking for it get a frame whenever the pointer moves over them. The build that reads the last moves of a press on the element sees where the pointer let go.
func (Element) PopoverMenu ¶
PopoverMenu gives the element a context menu, as ContextMenu does, which MyGo draws in the window with the theme's look, as a popover, rather than the system showing one of its own. It opens where the element is clicked with the secondary button, or Control-clicked on macOS, and, while the element or one inside it has the focus, below it when the menu key or Shift+F10 is pressed. build fills it with the items ContextMenu's function takes, and the item chosen reports Chosen as there:
row.PopoverMenu(func(m *ui.Menu) {
if m.Item("Rename").Shortcut(0, ui.KeyF2).Chosen() {
app.renaming = i
}
if m.Item("Pinned").Checked(note.pinned).Chosen() {
note.pinned = !note.pinned
}
m.Separator()
if m.Item("Delete").Disabled(note.locked).Chosen() {
app.delete(i)
}
})
The menu takes the focus as it opens and gives it back as it closes, to the element that had it. Up and Down move among its items, past those disabled, as do Home, End and typing the first letters of an item; Right opens a submenu and Left closes it, the other way round right to left (Direction); Enter and Space choose an item, Escape closes the submenu on top, and a press outside the menu closes it. It shows below and after where it opened, and on the other side where the window has no room. Assistive technology sees a menu of items, check box items and radio items, as the system's. ContextMenuBase is such a menu without a look, for items of a layout of one's own.
PopoverMenuButton draws the menu of a menu button so.
func (Element) PopoverMenuButton ¶
func (_handle Element) PopoverMenuButton(build func(m *Menu), options ...PopoverMenuButtonOptions) Element
PopoverMenuButton makes the element a menu button, as Menu does, whose menu MyGo draws in the window with the theme's look, as PopoverMenu draws a context menu, rather than the system showing one of its own. It opens below the element, or above it where the window has no room, as the pointer goes down on it, and for Enter, Space, Up or Down while it has the focus, which it takes. build fills it with the items Menu's function takes, and the item chosen reports Chosen as there:
more := ui.ButtonBase(c).Label("More").Padding(4).Radius(6)
more.Children(func() { ui.Icon(c, moreIcon).Size(16, 16) })
more.PopoverMenuButton(func(m *ui.Menu) {
if m.Item("Duplicate").Chosen() {
app.duplicate()
}
if m.Item("Delete").Disabled(app.locked).Chosen() {
app.delete()
}
})
The menu has the keys of PopoverMenu's, and takes the focus as it opens and gives it back as it closes, as there; a press on the element closes it too. Opened by the keyboard, it starts on its first item. Assistive technology sees a menu button, expanded while its menu shows, and the menu as PopoverMenu's. The function PopoverMenuButton is a button with such a menu, as MenuButton is one with a menu of the system's, and MenuBase a menu button without a look.
Its options place the menu elsewhere along the button, and let the app open and close it (PopoverMenuButtonOptions): the menu of a toolbar's button at the window's end lines up with the button's end, and closes from an event of the app's:
more.PopoverMenuButton(build, ui.PopoverMenuButtonOptions{
At: ui.AnchorBottomEnd, Self: ui.AnchorTopEnd, Open: &app.moreOpen,
})
func (Element) PositionInSet ¶
PositionInSet tells assistive technology which item of its set the element is, pos from 1, and how many items the set has, size, as ARIA's aria-posinset and aria-setsize: for an item of a list, list box, tree, menu or tab list of your own whose set is not what is built around it, as one built only where it shows, or a tree laid out flat in one column (with Level), so that screen readers read "3 of 50". Either at 0 or less is not given: the place the element's widget gives it, if any, stands.
for i := app.first; i < app.last; i++ { // only those in view
ui.Row(c).Role(ui.RoleOption).PositionInSet(i+1, len(app.results)).
Children(func() { ui.Text(c, app.results[i]) })
}
It wins over the place a ComboboxBase, SelectBase, MenuBase, Tree or GridView gives its items, which counts those it builds, as for a combobox showing the first 50 of 1,000 results. A List's rows keep theirs, which say which of all its rows they are, built or not, and place the rows of its table on macOS and Windows; a row or a cell of a grid of your own says its place with RowIndex and ColumnIndex.
func (Element) PreserveSpaces ¶
PreserveSpaces keeps the spaces the element's text ends its lines with, and a text of only spaces, with their advance, as CSS's white-space: break-spaces does: a gap made of spaces between two texts in a row, or the padding a monospaced column is aligned with. Without it spaces ending a line take no room, as with white-space: normal.
func (Element) PressCanceled ¶
PressCanceled reports whether the press of the element ended since the last frame without the pointer letting go, as Pointer Events' pointercancel: the system took it (a browser turning a touch into the page's scrolling, the window losing the mouse capture or the pointer's grab, a menu taking the release), or the window lost the keyboard. Such a press clicks nothing (Clicked) and ends no drag (DragEnded), and Pressed turns false: undo what the press began, as a preview a drag showed, rather than commit it.
dx, _, held := handle.Dragged()
switch {
case held:
app.preview += dx
case handle.PressCanceled():
app.preview = 0
case app.preview != 0:
app.width, app.preview = app.width+app.preview, 0
}
func (Element) Pressed ¶
Pressed reports whether the element is being pressed with the pointer's primary button, unless it is disabled. A press of another button, as a right-click's, is no press here, as CSS's :active and drags on the web have it: PressedButton tells which button presses the element.
func (Element) PressedButton ¶
PressedButton returns the button of the pointer pressing the element, 0 for the primary, 1 the secondary and 2 the middle, while the press lasts, wherever the pointer goes, as Dragged; ok is false while nothing presses it, or it is disabled. Pressed, Dragged, DragVelocity and DragEnded follow the primary button alone; an element that pans with the middle button, as a canvas, reads the button here and where the pointer goes with PointerPosition.
func (Element) PressedInside ¶
PressedInside reports whether the pointer went down since the last frame on the element, inside it, or in a popover attached to it, as PressedOutside reports one outside. Unlike Pressed and Clicked, the element does not take the pointer.
func (Element) PressedOutside ¶
PressedOutside reports whether the pointer went down since the last frame outside the element: on neither it, nor what it holds, nor the element it is attached to (AttachTo), nor the overlays attached to elements inside it, as the popover of one of its buttons. A popover closes then, the press going on to what is under the pointer, as PopoverBase does. The last press decides: one on the button opening a popover after a press elsewhere, as on a web view's page, in the same frame, keeps it open. A press before the element showed, as the one opening it, is not outside it: an Overlay opened by a press stays.
func (Element) PressedPointer ¶
func (_handle Element) PressedPointer() (PointerType, float32, bool)
PressedPointer returns the device pressing the element and how hard it presses, from 0 to 1, as of the press's last move, while the press lasts, as PressedButton; ok is false while nothing presses it, or it is disabled. As InputEvent.Pressure, a device that tells no pressure, as a mouse, presses 0.5. A signature pad widens its stroke with a pen's pressure, and goes by the pointer's speed for a mouse. Elements asking for it get a frame whenever the pointer moves or the pressure changes.
func (Element) Pretty ¶
Pretty keeps the last line of each paragraph of the element's text from holding a single word, as CSS's text-wrap: pretty does at least: the line before gives it a word, and the lines before stay as they are. A paragraph of body text then ends on more than one word, at no cost to the rest of its lines; Balance balances them all instead.
func (Element) RadialGradient ¶
func (_handle Element) RadialGradient(g RadialGradient) Element
RadialGradient fills the element with a radial gradient, its colors spreading out from a point (CSS's radial-gradient()), as a glow:
ui.Box(c).Size(160, 100).Radius(16).RadialGradient(ui.RadialGradient{
Stops: []ui.GradientStop{{ui.RGBA(99, 102, 241, 0.6), 0}, {ui.Transparent, 1}},
})
func (Element) Radius ¶
Radius rounds the corners: one radius for all, or top-left, top-right, bottom-right and bottom-left.
func (Element) Range ¶
Range tells assistive technology the range and the value of a slider, progress bar, meter or stepper of your own: value, from lo to hi. Step tells it how far the keys move the value.
func (Element) ReadOnly ¶
ReadOnly makes a text input show its text without letting the user change it: the text can still be selected and copied, from the keyboard too, as it takes the focus, without a caret; assistive technology reads it as read-only.
func (Element) Reverse ¶
Reverse lays the children out in the other direction: a Row from right to left, a Column from bottom to top, as CSS's row-reverse and column-reverse do. Justify's Start is then the right or the bottom.
func (Element) RightClicked ¶
RightClicked reports a click with the secondary button, as for a context menu.
func (Element) RightPercent ¶
func (Element) Role ¶
Role sets what the element is to assistive technology, for an element drawn as a widget it is not built from, such as a custom toggle.
func (Element) RoleDescription ¶
RoleDescription tells assistive technology what to call the element's role, in place of its own, as ARIA's aria-roledescription: "carousel" for a group of slides, and "slide" for each. Screen readers read it where they would read the role, so give it in the user's language, and keep the role, which says how to use the element. "" reads the role.
func (Element) Rotate ¶
Rotate rotates an element clockwise around its transform origin, which changes no layout sizes. An Icon keeps turning its SVG artwork around its center, as a spinner does:
spin := ui.Icon(c, loader)
spin.Rotate(spin.Loop("spin", time.Second, ui.Linear) * 360)
Use Transform(Rotation(degrees)) to rotate an icon's entire border box.
func (Element) RotateX ¶
RotateX turns the element in 3D around the horizontal axis through its origin, after its existing transform, as RotationX: follow it with Perspective to see it in depth.
card.RotateX(30).Perspective(800)
func (Element) RotateY ¶
RotateY turns the element in 3D around the vertical axis through its origin, after its existing transform, as RotationY: a card turning over shows its back past 90 degrees, mirrored.
card.RotateY(flip * 180).Perspective(800)
func (Element) RowCount ¶
RowCount tells assistive technology how many rows a table, grid or tree grid of your own has, built or not, header rows included, as ARIA's aria-rowcount: one that builds only the rows in view says how many it has, which screen readers read with the rows' RowIndex, as "row 4,121 of 10,000". The rows of a List and a Table say which of all they are themselves.
func (Element) RowDoubleClicked ¶
RowDoubleClicked reports, while a row of a List or a Table builds, that the row was double-clicked since the last frame with the pointer over the element: a cell sees its row's double click this way and leaves the click to the row, which chooses, where DoubleClicked would take it.
ui.Table(c, &app.list, cols, len(app.rows), func(row, col int) {
cell := ui.Box(c).FillWidth().Children(func() { ui.Text(c, app.rows[row][col]) })
if cell.RowDoubleClicked() {
app.edit(row, col)
}
})
func (Element) RowIndex ¶
RowIndex tells assistive technology the place of a row, or of a cell, among all the rows of its table, grid or tree grid, from 1 for the first, header rows included, as ARIA's aria-rowindex: for one that builds only the rows in view, with its RowCount. A cell takes its row's.
func (Element) RowSpan ¶
RowSpan makes the element span n rows of its grid, or, for a negative n, every row from its start to the last the grid sets. A cell of a table or a grid tells assistive technology it covers them, as ARIA's aria-rowspan: the cells of the rows below it then say their columns with ColumnIndex where they follow it.
func (Element) RowTracks ¶
RowTracks sets the grid's first rows; those it adds after fit their content.
func (Element) RowWidth ¶
RowWidth makes the rows of a List at least w DIPs wide, as the columns of a table ask: where they are wider than the list, it scrolls sideways too, and its rows grow to its width where they are not. A header above the rows goes with them through ScrollWith:
head := ui.Row(c).Clip().Padding(0, 8).Children(app.columnTitles) list := ui.List(c, &app.rows, n).Padding(0, 8).RowWidth(app.columnsWidth()) list.Rows(app.row) head.ScrollWith(list)
func (Element) ScrollIntoView ¶
func (_handle Element) ScrollIntoView(options ...ScrollIntoViewOptions) Element
ScrollIntoView scrolls the containers around the element as little as shows it, once the frame is laid out: an element added in this frame comes into view with it. Call it in the frame it should come into view, as when it is added or chosen: in every frame, it would keep the user from scrolling it away.
Its options line the element up elsewhere in the containers, or glide there, as the web's scrollIntoView options do: the current match of a search, centered smoothly.
if app.matchMoved {
hit.ScrollIntoView(ui.ScrollIntoViewOptions{Block: ui.ScrollCenter, Animation: &ui.Smooth})
}
func (Element) ScrollSnap ¶
ScrollSnap makes the scroll container (Scroll, ScrollHorizontal, ScrollBoth, List) come to rest at the places the elements in it mark with SnapAlign, as CSS's scroll-snap-type does, on the axes it scrolls:
- a touchpad, its momentum after a fling, and a finger on a touchscreen glide on to the nearest once they have settled, and so does a thumb of a scroll bar once it is let go;
- a notch of a wheel, the arrow keys, Page Up and Page Down, Home and End and a press on a scroll bar's track go to the next place that way, past where it was, as far as they scroll.
A place lines an element up with the container's content box, inside its padding, so that the first of a strip of cards rests where it starts. An element larger than the view rests anywhere it fills the view. Resting at an element, the container stays at it as the layout moves it, as when the window resizes, and an element of one coming into view (ScrollIntoView, the focus) lines it up. Where the app scrolls the container, with its ScrollState, ScrollTo or a List's ListState, it stays. While the desktop asks for less motion, it rests at once.
ui.ScrollHorizontal(c).ScrollSnap(ui.SnapMandatory).Padding(16).Gap(12).Children(func() {
for _, card := range app.cards {
cardView(c, card).SnapAlign(ui.Start)
}
})
func (Element) ScrollWith ¶
ScrollWith moves the element's content sideways as far as scroller, a scroll container, scrolls its own, as a table's header goes with its rows. Clip the element, so that what goes out of it does not show.
func (Element) ScrollbarInsets ¶
ScrollbarInsets moves a scroll container's scroll bars in from its edges, CSS style as Padding: the vertical bar runs from top DIPs below its top to bottom DIPs above its bottom, right DIPs in from its right, and the horizontal bar from left to right DIPs in, bottom DIPs up. A bar keeps clear so of what floats over the content, as a toolbar the content scrolls under, which AppKit's scrollerInsets and UIKit's scroll indicator insets do:
ui.Scroll(c).Fill().Padding(64, 16, 16).ScrollbarInsets(64, 0, 0)
func (Element) Scrollbars ¶
Scrollbars controls the overlay indicators and their pointer hit targets on this scroll container. They show on hover by default. With false, scrolling by wheel, TrackScroll, keyboard focus and accessibility remains available. It applies to Scroll, ScrollHorizontal, ScrollBoth, List and Table, not the internal indicators of custom controls such as a code editor (whose State has NoScrollbars), and is not inherited.
func (Element) Search ¶
Search makes a text input one for searching, in the frames that call it, as ARIA's searchbox and HTML's <input type=search>: assistive technology reads it as a search field, as it reads a SearchField's input, while the view draws it as it likes, with an icon and a clear button of its own, and handles its keys. Name it with Label.
ui.TextInput(c, &app.query).Placeholder("Search").Label("Search mail").Search()
func (Element) Selectable ¶
Selectable lets the user select and copy text by dragging, double-clicking a word, triple-clicking a line, or using Shift with the arrows. Its context menu has Copy and Select All; Cmd+C copies the selection.
On a container, its Text and RichText descendants share one selection. Copy joins their selected text with newlines, in the order they were built. Nested Selectable containers have independent selections. Text inside controls, such as buttons and text inputs, keeps the control's interaction. Unselectable excludes a subtree. On a Text or RichText alone, the selection stays within that paragraph. Inline elements share their paragraph's selection; set Selectable on the paragraph.
func (Element) Selected ¶
Selected shows the element as chosen among its siblings, in the accent color, as a row of a list, and tells assistive technology it is.
func (Element) SelectedTexts ¶
func (_handle Element) SelectedTexts() []SelectedText
SelectedTexts returns the parts of the paragraphs that the selection of a Selectable container holds, in the order they were built, or none, as of the last frame: to copy them otherwise, as a context menu's item does.
func (Element) SelectionColor ¶
SelectionColor sets the highlight of selected text in the element and the text inside it, as text on a colored bubble needs one that shows on it; the theme's Selection is the highlight elsewhere.
func (Element) SetChanged ¶
SetChanged reports the element's value as changed in this build pass, as a widget of your own whose input changed what it edits: Changed returns true for it, as for the widgets' own.
func (Element) SetTextSelection ¶
SetTextSelection selects the runes of a text input from start to end, or puts the caret at start when they are equal, and scrolls it into view: the caret after a word the app completed. The offsets are kept within the text.
func (Element) Settled ¶
Settled reports whether the value animated under key, by AnimateTo, Animate, Spring or Keyframes, rests at its target in this frame: true for an unknown key.
func (Element) Shadow ¶
Shadow adds a box shadow, offset by x and y, blurred by blur and grown by spread DIPs. As CSS's box-shadow, it shows only outside the box: a translucent background does not show it through.
func (Element) Shortcut ¶
Shortcut reports whether the key with exactly the modifiers mods was pressed while the element or one of its descendants had the focus. The innermost element handling a key gets it; a disabled one handles none.
func (Element) Shrink ¶
Shrink sets how much the element gives up when its siblings do not fit (1 by default, 0 never).
func (Element) SingleLine ¶
SingleLine keeps the element's text on one line, ending it with an ellipsis when it does not fit.
func (Element) Skew ¶
Skew slants the element after its existing transform, around its origin, by x degrees along the horizontal axis and y along the vertical.
func (Element) SnapAlign ¶
SnapAlign marks a place where the nearest scroll container around the element rests, if it snaps (ScrollSnap): where the element's start, center or end, as a is Start, Center or End, lines up with the container's, on both axes, as CSS's scroll-snap-align. Start is the left of what scrolls sideways, its right right to left (Direction), and the top of what scrolls vertically.
func (Element) SnapAlignX ¶
SnapAlignX marks a place as SnapAlign does, sideways only: a container that scrolls both ways rests anywhere vertically.
func (Element) SnapAlignY ¶
SnapAlignY marks a place as SnapAlign does, vertically only.
func (Element) Sort ¶
func (_handle Element) Sort(dir SortDirection) Element
Sort tells assistive technology the order a table's rows are sorted in by the column whose header the element is (RoleColumnHeader), as ARIA's aria-sort: for a sortable table of your own, whose headers show it. Table's headers tell it from ListState.Sort and SortBy.
func (Element) SplitReset ¶
SplitReset makes a double click on the divider of a Split put the first pane at v, in the split's own unit: DIPs for Split and SplitVertical, a percentage for SplitPercent and SplitVerticalPercent. A split without it keeps its size on a double click. The value is kept even when the window is too small to show it, so the pane takes it back when there is room again.
ui.Split(c, &app.sidebar, app.files, app.editor).SplitReset(220)
func (Element) Spring ¶
func (_handle Element) Spring(key any, target float32, options ...SpringOptions) float32
Spring returns a value following target with a spring, as AnimateTo does with Animation{Spring: options}: Smooth's spring without options.
func (Element) Start ¶
Start and End place an Absolute element from the side lines start and from the other, as Left and Right do, as CSS's inset-inline-start and inset-inline-end: from the left and the right, or the right and the left right to left. On an element in its parent's layout, they move it as relative positioning does.
func (Element) StartPercent ¶
StartPercent and EndPercent place the element as Start and End do, by a percentage of the parent's width.
func (Element) Step ¶
Step makes the values of a slider lo and the multiples of step from it, which the arrows move between, as a StepSlider's. Of a range of your own (Range), it tells assistive technology how far the keys move the value.
func (Element) Sticky ¶
Sticky keeps the element in its parent's flow, where it takes its room, and holds it inside the scroll container around it while its parent is in view, as CSS's position: sticky does: Top, Right, Bottom and Left (or Start and End, and their percentages of the container's size) say how far in from the container's edges, inside its border, it stays. It moves no further than its parent's content box, so the parent leaving the view takes it along, and the next one's comes up in its place: a day's heading at the top of a timeline until the next day pushes it out, or the check box choosing all the rows at the left of a table scrolling sideways.
ui.Scroll(c).Fill().Children(func() {
for _, day := range app.days {
ui.Column(c).Children(func() {
ui.Text(c, day.Title).Bold().Background(t.Surface).Sticky().Top(0)
for _, ev := range day.Events {
eventRow(c, ev)
}
})
}
})
Each axis follows the nearest container scrolling that way, or one following another sideways (ScrollWith), or else the window: a heading in a table scrolling sideways in a page scrolling down sticks to the page's top and to the table's start. Where both insets of an axis are set and the container is too small for both, Top wins, and Left, or Right right to left. Without insets, the element stays where the flow puts it. It paints above its siblings, as Absolute elements do, and the pointer, assistive technology and the focus ring find it where it shows; the focus and assistive technology still take it in its place among them. Sticky does nothing to an Absolute element, nor to one inside a text.
func (Element) Strikethrough ¶
Strikethrough strikes text through.
func (Element) Stripes ¶
Stripes draws stripes of c over the background, width DIPs wide with gap DIPs between them, running at angle degrees clockwise from upwards: 0 draws vertical stripes, 90 horizontal ones, and 45 slanting ones like slashes, as to mark what is unavailable.
func (Element) Submitted ¶
Submitted reports whether Enter was pressed in a single-line text input in this build pass.
func (Element) TabSize ¶
TabSize puts the tab stops of the element's text every n spaces of its font from the start of each line, as CSS's tab-size: a tab advances to the next of them, as a code block indents with tabs of 2 or 4 columns. A space is as wide as the font's, letter spacing included. Without it, or with n at 0, tabs advance as the system's text stack sets them, which differs between systems.
func (Element) TabStop ¶
TabStop makes the element focusable, and sets whether Tab and Shift+Tab stop at it, as they do at a Focusable element. One that is no tab stop is HTML's tabindex="-1": it takes the focus from a click, from Focus and AutoFocus, and from assistive technology, while Tab passes over it, on to what is inside it and after it: a container that takes the focus to hold its keys, as a card or a dialog's panel, without coming before its own controls.
func (Element) TextAnchorCaret ¶
TextAnchorCaret returns the selection of a text input as offsets in runes into its text, from where it was started to its caret: the anchor is after the caret when the selection was made backwards.
func (Element) TextBackground ¶
TextBackground fills the lines of text behind it with c, as a highlight.
func (Element) TextCaret ¶
TextCaret has the element take text from the system's input methods while it has the keyboard focus, with their composition at r, the caret, relative to the element's box: candidate windows show there. Its InputText and Compose events (HandleInput) bring the text.
func (Element) TextRanges ¶
TextRanges styles runs of a text input's text, in the frames that call it. Ranges may overlap and nest, as the attributes of an attributed string do: where they do, each of Color and Weight is that of the last range given that sets it, across the calls of the frame. They follow the text as it is: an app that finds them in the text finds them again as it changes. A password shows none; an input method's composition shows unstyled between them.
func (Element) TextSelection ¶
TextSelection returns the selection of a text input as offsets in runes into its text, the caret where start equals end, as the app reads it to complete the word being typed.
func (Element) TextShadow ¶
TextShadow casts a shadow of the element's text, as CSS's text-shadow: the shapes of its glyphs, offset by x and y DIPs, blurred by blur, in c, under the glyphs and their strokes, as a chart's labels over its bars or a caption over a photo take one to stand out. The text of the elements inside takes it too, and theirs where they set one; a transparent c casts none, where those around it cast one. A span's Shadow sets one for its text. The shadow of color glyphs, as emoji, is that of their pixels' shape; underlines and strikethroughs cast none.
ui.Text(c, "Golden hour").TextColor(ui.RGB(255, 255, 255)).TextShadow(0, 1, 4, ui.RGBA(0, 0, 0, 0.6))
func (Element) TextStroke ¶
TextStroke strokes the outlines of the glyphs of text width DIPs wide in c, under their fill, as CSS's -webkit-text-stroke with paint-order: stroke fill: the half of the stroke outside the glyphs shows around them, a halo of c, as a chart's labels over its bars take one of the background's color to stand out. A text's strokes all go under all its glyphs, so that one glyph's stroke never covers its neighbor; the stroke goes around the edge of the pixels of color glyphs, as emoji. Underlines and strikethroughs are not stroked. A width of 0 strokes nothing, where the elements around it stroke their text.
func (Element) Timeline ¶
func (_handle Element) Timeline(key any, o TimelineOptions) *Timeline
Timeline returns the timeline the element keeps under key, playing it as o says. Every tween added to it shares one playhead, and returns the value it shows in this frame.
card := ui.Column(c)
tl := card.Timeline("intro", ui.TimelineOptions{Run: app.opened})
x := tl.Tween(ui.Tween{From: -200, To: 0, Duration: 400 * time.Millisecond})
card.Translate(x, 0)
Key tells apart the timelines of the element, as it does its Keyframes, and an element asks for each of its timelines once per build. Play the timeline again, or a changed one, by changing o.Run. The *Timeline is valid while the view builds this frame.
While the desktop asks for less motion (Preferences.ReduceMotion), a timeline that would play is at once where it would come to rest, unless o's NonMotion says it moves nothing, but Seek, Progress and Paused still put and hold its playhead, as a drag still moves a Draggable element. DisableAnimations does not change a timeline, which plays on its own, as Keyframes do: jump it with Seek.
func (Element) Tooltip ¶
Tooltip shows s by the element when the pointer rests on it, or the keyboard focus comes to it, as TooltipBase does: above the element, centered, or below it where there is no room above. It describes the element to assistive technology where Description does not.
func (Element) Top ¶
Top, Right, Bottom and Left place an Absolute element. On an element in its parent's layout, they move it from where the layout put it, as CSS's relative positioning does, without moving its siblings.
func (Element) TopPercent ¶
TopPercent, RightPercent, BottomPercent and LeftPercent place the element as Top, Right, Bottom and Left do, by a percentage of the parent's height or width.
func (Element) TrackLines ¶
TrackLines keeps in l where the text area lays out its lines.
func (Element) TrackScroll ¶
func (_handle Element) TrackScroll(s *ScrollState) Element
TrackScroll keeps the scrolling of a scroll container (Scroll, ScrollHorizontal, ScrollBoth, List) in *s: the container shows its content from s.X and s.Y, and writes there as the user scrolls it. The app reads where it is, scrolls it by setting them, and keeps a place with a ScrollState of its own for each page the container shows.
// A log that follows its end, unless the user scrolled up from it.
if app.log.Y >= app.log.MaxY {
app.log.Y = math.MaxFloat32
}
ui.Scroll(c).TrackScroll(&app.log).Children(app.lines)
A List keeps its place by its rows instead, and scrolls to a row with its ListState.
func (Element) Transform ¶
Transform sets the element's visual transform, in place of the one it had, TranslatePercent's included. Its origin is the center of its border box unless TransformOrigin changes it.
func (Element) TransformOrigin ¶
TransformOrigin sets the origin as fractions of the border box: (0,0) is the top-left and (0.5,0.5) the center. Values outside the box are allowed. Translation does not depend on the origin.
func (Element) Transition ¶
func (_handle Element) Transition(t ElementTransition) Element
Transition animates the element as t asks. The element needs the same ID from frame to frame: a Key, or the same place among its siblings. Elements that the change moves as well need a Transition of their own to move smoothly, the same one to move in step with it, as the rows of a list:
for _, it := range app.items {
ui.Row(c).Key(it.ID).Transition(rowTransition).Children(func() {
ui.Text(c, it.Title)
})
}
Changes made by resizing the window do not animate. While the desktop asks for less motion (Preferences.ReduceMotion), nothing moves: colors still change smoothly, and an Enter or Exit that fades or blurs without collapsing fades and blurs in place.
func (Element) Transitioning ¶
Transitioning reports whether the element's Transition was moving it, or changing its colors, or its pose (AnimatePose) or Draggable was moving it, in the frame before: false once it is where it goes.
func (Element) TranslatePercent ¶
TranslatePercent moves the element by x and y percent of its own width and height, as CSS's translate(-50%, -50%) does: of its border box as the frame lays it out, so that it is in place from its first frame and follows its size as it changes. It acts after the element's other transforms, wherever it is called among them, and before its pose (AnimatePose), and adds to a TranslatePercent before it. A callout centered above a point:
ui.Box(c).Absolute().Left(p.X).Top(p.Y).TranslatePercent(-50, -100)
func (Element) TranslateZ ¶
TranslateZ moves the element z DIPs toward the viewer after its existing transform, as TranslationZ: follow it with Perspective to see it nearer or farther. A card lifting toward the viewer as it turns over:
card.RotateY(turn).TranslateZ(lift).Perspective(800)
func (Element) UnderlineOffset ¶
UnderlineOffset puts underlines v DIPs below the baseline, measured to their top, or above it when negative, as CSS's text-underline-offset: a link's underline a few pixels lower than the font puts it, clear of the descenders. Underlines skipping the ink of descenders skip it where they then are. The font places them otherwise.
func (Element) Unselectable ¶
Unselectable excludes a paragraph or container subtree from a surrounding Selectable container. A Selectable container nested inside it can provide a selection of its own. For inline elements, set it on their paragraph.
func (Element) Valid ¶
Valid reports whether the element belongs to the active build pass. Checking validity does not trigger expired-handle diagnostics.
func (Element) Value ¶
Value sets what assistive technology reads as the element's value, as the choice a button opening a popup shows, or the text of a range's value beside its number (aria-valuetext), as "3 of 10 steps".
func (Element) Velocity ¶
Velocity returns how fast, in its units per second, the value animated under key goes in this frame: zero for one at rest or unknown.
func (Element) Vertical ¶
Vertical makes a SliderBase go up, from lo at the bottom of its content box to hi at the top, and tells assistive technology so. Pad it by half the thumb's height, rather than its width. Slider, drawn across, stays so.
func (Element) WavyUnderline ¶
WavyUnderline underlines text with a wave, as spell checkers mark words.
func (Element) WidthPercent ¶
WidthPercent sets the width as a percentage of the parent's.
func (Element) WindowToLocal ¶
WindowToLocal maps a window point into the previous frame's border box. ok is false for singular transforms, which take no pointer input.
func (Element) WrapReverse ¶
WrapReverse wraps the children onto lines that stack the other way: up in a Row, to the left in a Column.
func (Element) ZIndex ¶
ZIndex orders the element's painting among its siblings, as CSS's z-index does: those with a higher value paint later, above those with a lower one, whatever their order in the tree, and take the pointer first where they overlap. Siblings with the same value paint as they would without one: those in the flow in the order they were built, then the absolute and sticky ones in theirs. The default is 0; a negative value paints the element under its siblings, still above its parent's background. The copy of an element leaving with its Exit (ElementTransition) keeps the z-index the element had, under its siblings of the same one: a dialog fading out stays above the page.
It moves the element with all that is inside it, as one, among its siblings alone: it does not reach past its parent, which still clips it where it clips, nor mix the elements inside it with those of other parents, as if each element with a value other than 0 made a stacking context, as in CSS. Nothing else changes: the layout, the order Tab moves the focus in and what assistive technology reads follow the tree.
A stack of overlapping avatars, the first on top:
ui.Row(c).Children(func() {
for i, u := range users {
a := ui.Avatar(c, u.Name, u.Photo).ZIndex(len(users) - i)
if i > 0 {
a.Margin(0, 0, 0, -8)
}
}
})
A cell of a grid growing as the pointer is over it, above the cells after it:
cell := ui.Box(c).Size(80, 80)
if cell.Hovered() {
cell.Scale(1.2, 1.2).ZIndex(1)
}
The window's content stays under its overlays (Overlay) whatever its z-index, and overlays keep the order they open in; an element inside a text (inline) paints with its text.
type ElementTransition ¶
type ElementTransition struct {
// Duration is how long a change takes: 200 ms when zero, and none
// when negative, which shows every change, the Enter and the Exit at
// once, as for an app asking for less motion of its own.
Duration time.Duration
// Ease is how the element goes, as for AnimateWith: EaseOut when nil.
Ease Easing
// Animation, if set, is how changes go instead of Duration and Ease:
// with a spring (Snappy, …), a change on the way keeps the element
// going as it went; with a Delay, changes wait, as the rows of a list
// entering one after another.
Animation *Animation
// ExitDuration and ExitEase, if set, are how long the Exit takes and
// how it goes, in place of Duration and Ease, or of Animation's spring
// (whose Delay still holds it): a popup that comes in over 150 ms and
// goes over 100. When zero, ExitDuration is Duration's, or about as
// long as Animation's spring; when negative, the element goes at once,
// without a copy. ExitEase is Ease's, or that of Animation's curve,
// when nil.
ExitDuration time.Duration
ExitEase Easing
// Position, Size, Colors and Shadows choose what animates: where the
// element is in its parent, its width and height (its content laid out
// at each size on the way), its background and border colors, and its
// shadows (Shadow, InsetShadow), as a resting shadow fading on hover.
// None set animates them all.
Position, Size, Colors, Shadows bool
// Width and Height, in place of Size, animate the element's width or
// its height alone, as CSS's transition-property lists one of them:
// the other follows the layout at once, as a panel springing open
// while the split view holding it is dragged wider.
Width, Height bool
// Enter, if set, is where the element comes from as it appears in a
// parent that the last frame showed: it starts there, and goes to its
// place.
Enter *Motion
// Exit, if set, is where the element goes once it is no longer built,
// while its parent still is: a copy of it, as the last frame showed
// it, goes there under its siblings of the same z-index (ZIndex),
// taking neither room, the pointer nor the focus, and is then gone. The parent's ChildExit, in the
// frame it goes, says where it goes instead.
Exit *Motion
// AfterExits holds the element appearing while copies of its siblings
// leave with their Exit: it takes its place unseen, and comes in with
// its Enter once they are gone, so that its parent shows one of them
// at a time, as a panel that finishes leaving before the next one
// appears.
AfterExits bool
// Match, if set, is an identity the element shares with one that the
// frame before showed elsewhere, even in another parent, as a photo's
// thumbnail in a grid and the photo in a detail view: the element
// appearing comes from where that one was, at its size and in its
// colors, as SwiftUI's matchedGeometryEffect and Motion's layoutId.
// Use a value of a type of your own, as a struct of the photo's ID.
Match any
// Fly, with a Match, flies the element appearing from where the other
// was, as Keynote's Magic Move and Flutter's Hero do: from its
// corners, opacity, text color and transform (in 3D too), and from the
// transforms of the elements around it, drawn over the rest of the
// window (or of its overlay) on the way, out of the clips around it,
// where it takes the pointer. The other, flying too, goes with it,
// fading out under it, rather than as its Exit says.
Fly bool
// ScaleContent shows the element's size changing, as it resizes or
// comes from the element of its Match, by scaling it from its own size
// rather than laying its content out at each size on the way: its text
// keeps its lines, growing or shrinking with it, as a title into a
// heading, and a picture stretches with its box.
ScaleContent bool
}
ElementTransition animates an element (Element.Transition) from what the last frame showed to what the layout makes of it in this one: where it is in its parent, its size, its background and border colors, and its shadows. Enter and Exit animate it as it appears and as it goes:
ui.Row(c).Key(item.ID).Transition(ui.ElementTransition{
Enter: &ui.Motion{Collapse: true},
Exit: &ui.Motion{Collapse: true},
})
type FillRule ¶
type FillRule uint8
FillRule is which points inside a path's subpaths a Painter fills, as SVG's fill-rule and clip-rule say, where they overlap or one is inside another.
const ( // NonZero fills a point that the subpaths wind around more times in // one direction than in the other: a subpath inside another one, // drawn the same way round, fills too, and one drawn the other way // round leaves a hole. The default, as SVG's nonzero. NonZero FillRule = iota // EvenOdd fills a point that the subpaths go around an odd number of // times, whichever way: a subpath inside another one leaves a hole, // as a ring of two circles, as SVG's evenodd. EvenOdd )
type Fit ¶
type Fit uint8
Fit says how an image fills its element.
const ( // Contain scales the image to fit inside the element, keeping its // aspect ratio. Contain Fit = iota // Cover scales the image to cover the element, cropping it. Cover // FillBox stretches the image to the element. FillBox // ScaleDown shows the image at its own size, or as Contain does where // that is smaller. ScaleDown // NaturalSize shows the image at its own size, centered and cropped. NaturalSize )
type Font ¶
type Font struct {
Family string
Size float32
Weight int
Italic bool
Features string
// Lang is the language of the text, as for Element.Lang; "" is the
// language the app shows.
Lang string
// LineHeight is the height of a line of text ShapeText and
// ShapeRichText lay out, as a multiple of Size, as Element.LineHeight
// takes it: 1.8 gives CJK prose its usual leading. 0 takes the font's
// own. Metrics and Shape ignore it.
LineHeight float32
// Thicken draws the glyphs with a thicker stroke, as Ghostty's
// font-thicken: on macOS, with Core Text's font smoothing at its
// strongest, whatever the color and the user's setting. It changes
// nothing elsewhere.
Thicken bool
// Antialiased draws the glyphs without font smoothing, thinner, as
// browsers draw text styled -webkit-font-smoothing: antialiased on
// macOS, for drawings that match a web page's. It changes nothing
// elsewhere.
Antialiased bool
}
Font is a font for text a Painter draws itself (Shape): a family list as Element.Font takes it, a size in DIPs (14 when 0), a weight from 100 to 900 (400 when 0), italics, and OpenType features as Element.FontFeatures takes them, comma separated.
type FontFamily ¶
type FontFamily struct {
// Name is the family as Font and Theme take it.
Name string
// Monospaced is whether its regular font gives every character the
// same advance, as a terminal's or a code editor's font setting
// offers.
Monospaced bool
// Registered is whether the app registered it with RegisterFont, under
// Name: the name it gave, or the font's own when it gave none.
Registered bool
}
A FontFamily is a font family text can use, as FontFamilies lists it.
func FontFamilies ¶
func FontFamilies() []FontFamily
FontFamilies lists the font families text can use, as a font setting offers them: the app's registered ones first, then the system's, each once, sorted without regard to case. A font registered under a name the app gave is listed under that name alone. Browsers do not tell what fonts they have: there the list holds the registered families alone, and a family is Monospaced once its font has loaded.
The first call asks the system for its families, which takes a while with many fonts installed (tens of milliseconds on a Mac with hundreds), without holding up the windows' text; later calls reuse that list, until RegisterFont, so fonts installed while the app runs show after a restart. It is safe from any goroutine.
type FontMetrics ¶
type FontMetrics struct {
Ascent, Descent, LineGap float32
}
FontMetrics are the vertical metrics of a font, in DIPs: how far its glyphs reach above and below the baseline, and the gap it leaves between lines.
type GPUTexture ¶
GPUTexture is a bitmap-like GPU-composed image usable by a native renderer. WebGPU canvases, imported WebGPU textures, and live native UI layers implement it. Constructors remain backend-specific; this interface is the backend-neutral composition contract.
type Glyph ¶
type Glyph struct {
// Cluster is the rune of the text the glyph's cluster starts at, and
// Runes how many runes the cluster holds: a ligature holds several,
// and so does a character with combining marks, whose glyphs share
// the cluster.
Cluster, Runes int
// X is the left of the glyph's advance from the start of the text,
// and Advance its width. Move X to draw the glyph elsewhere, as in the
// cell of a grid.
X, Advance float32
// RTL marks a glyph of a right-to-left run, as of Hebrew or Arabic,
// whose clusters go from right to left: its cluster's first rune is
// at the right of its advance.
RTL bool
// contains filtered or unexported fields
}
Glyph is a glyph of text that Shape placed, which Painter.Glyphs draws.
func Shape ¶
Shape shapes s in font f, on one line, for Painter.Glyphs: the system's text engine finds the font, falls back to others for what it lacks, and applies ligatures and kerning. Unlike the text of elements, which ui caches by content, it caches nothing: keep the glyphs of text drawn in several frames.
The glyphs are in visual order, on every platform, as they show from left to right: X ascends, and through a right-to-left run Cluster descends, with RTL set. Find the glyphs of a range of runes by their Cluster and Runes, not by their place in the slice; the glyphs of a cluster are next to each other.
type GradientStop ¶
GradientStop is a color of a gradient (LinearGradient, ConicGradient, RadialGradient) and its place along it, from 0 to 1, as CSS's color stops are. The gradient shows its first color before its first stop, its last after its last, and between two stops their colors blended; two stops at one place make a sharp edge. A gradient takes 32 stops at most, in sRGB.
type GridState ¶
type GridState struct {
Handle
// Key returns an identity for item i, as ListState.Key does for a
// row: the choice and the items' state follow it.
Key func(item int) any
// Selected, when set, lets a click choose an item, as the arrows do
// while the grid has the keyboard focus: *Selected is the item chosen,
// -1 for none. The grid's Changed reports a new choice, and its
// Submitted a double click or Enter.
Selected *int
// Selection, when set, lets the user choose several items, held by
// their keys, as a List's Selection: Cmd-click (Ctrl-click on Linux
// and Windows) adds an item or takes it out, Shift-click and Shift
// with the arrows choose those from the item last chosen, and Cmd+A
// chooses all. Selected, set as well, is the item last chosen.
Selection Selector
// Label returns the text of item i: typing its first letters while
// the grid has the focus chooses it, and assistive technology reads it
// as the item's name.
Label func(item int) string
// Reorder, when set, lets the user drag items to another place in the
// grid, as ListState.Reorder does rows: the items chosen, when the item
// dragged is one, else that item, in order, and the item they go
// before, the number of items for the end.
Reorder func(items []int, to int)
// contains filtered or unexported fields
}
GridState is the state of a GridView: how its items are told apart and chosen, as a List's rows are, and the place of its rows.
func (*GridState) ScrollIntoView ¶
ScrollIntoView scrolls the grid as little as shows item.
type Handle ¶
type Handle struct {
// contains filtered or unexported fields
}
Handle identifies a control across builds. Bind it to an Element on each pass. One handle may have separate bindings in several windows. Queries take a Context and read committed identity, regardless of build order. Use on the UI thread; background work uses Window.Update.
func (Handle) Bounds ¶
Bounds returns the control's box in the committed frame, in window DIPs. It works between builds on the UI thread; hidden or closed controls return an empty box. Use this instead of retaining an Element in input callbacks.
func (*Handle) CancelFocus ¶
CancelFocus cancels pending focus in the selected window, or every binding.
func (*Handle) Focus ¶
Focus requests focus, waiting while the control is hidden. Supply a Context to select a window. Without one, a handle must have at most one open window. A request made before its first binding waits for that binding.
func (Handle) FocusWithin ¶
func (Handle) HandleLayerInput ¶
func (r Handle) HandleLayerInput(c *Context, ev InputEvent) bool
HandleLayerInput sends ev to the layer bound to r with the geometry versions that binding last built. Pointer, wheel and leave events are refused if either the UI snapshot or surface map changed after that build, so a camera or simulation tick cannot resolve input against pixels that have not been presented. Keyboard and text events still pass through. Render the layer and invalidate its presenters when NeedsFrame reports true, as with HandleSurfaceInput.
func (*Handle) OnShortcut ¶
OnShortcut declares an action before or after Bind. A control omitted from this pass takes no shortcut. Actions run once after bindings are complete.
func (*Handle) RequestFocus ¶
RequestFocus is an alias for Focus.
type ImageOptions ¶
type ImageOptions struct {
// FlipX mirrors the part left to right, FlipY top to bottom.
FlipX, FlipY bool
// Tint multiplies its colors and alpha, as a colored filter would;
// zero for none.
Tint Color
}
ImageOptions are how Painter.ImageRegion draws a part of a bitmap.
type ImageSource ¶
type ImageSource interface {
// contains filtered or unexported methods
}
ImageSource is what Image shows: a *Bitmap, or an *SVG in its own colors.
func DecodeImage ¶
func DecodeImage(data []byte) (ImageSource, error)
DecodeImage decodes a picture whose format is not known up front, as one downloaded: a bitmap of what DecodeBitmap decodes, else an SVG of a size, else DecodeBitmap's error.
type InputEvent ¶
type InputEvent struct {
Kind InputKind
Key Key
// PhysicalKey is Key by position on an ANSI US keyboard, whatever the
// layout types: the S key is KeyS on a Cyrillic layout too, where Key
// is KeyUnknown. KeyUnknown where the platform does not report it.
PhysicalKey Key
// Code is the key by its position on any keyboard, with the sides of
// the modifiers told apart, as CodeShiftLeft; CodeUnknown where the
// platform does not report it, as for a mouse's side buttons, whose
// keys are KeyBack and KeyForward. It alone names a key whose Key is
// KeyUnknown, as a modifier on its own or Caps Lock.
Code KeyCode
Mods Modifiers
Repeat bool
// Text of InputText, InputCompose and InputCommand, and Caret the
// rune of an InputCompose's caret.
Text string
Caret int
// X and Y locate the pointer relative to the element's box.
X, Y float32
// Button is 0 for the primary button, 1 the secondary and 2 the
// middle.
Button int
Clicks int
// Canceled marks an InputPointerUp that ends the press without the
// pointer letting go, as Pointer Events' pointercancel: the system
// took the press (a browser's pointercancel, as a touch turns into
// the page's scrolling, the window losing the mouse capture or the
// pointer's grab, a menu taking the release), the window lost the
// keyboard, or a frame built the element no more. The release still
// comes, so that what the press holds lets go, but it is no
// completed gesture: undo what the press began rather than commit it,
// as a tap, a drop or the end of a scrub. Elements that ask about
// their input as they are built get no click of it (Clicked,
// RightClicked), no drop (Drop) and no end of a drag (DragEnded).
Canceled bool
// Pointer is the device of InputPointerDown, InputPointerUp and
// InputPointerMove, and Pressure how hard it presses, from 0 to 1, as
// Pointer Events' pointerType and pressure: a pen's or a finger's
// where the system tells it, else, as for a mouse, 0.5 while a button
// is down and 0 while none is. A pen's pressure changing where it
// stands comes as an InputPointerMove too.
Pointer PointerType
Pressure float32
// DX and DY are what InputScroll scrolls by, in local axes; positive DY moves the view
// down the content.
DX, DY float32
Precise bool
Momentum bool
// Scale is what InputZoom zooms by.
Scale float32
// Start and End are the runes InputSelect selects.
Start, End int
// Time is when the event came, by the clock of the window's frames
// (Context.Now), which a Tester's clock is in tests.
Time time.Time
}
InputEvent is input an element takes as it comes (HandleInput).
type InputKind ¶
type InputKind uint8
InputKind is the kind of an InputEvent.
const ( // InputKeyDown and InputKeyUp report a key with the modifiers held; // Repeat marks the auto-repeat of a key held down. A key that types // text comes before the text, an InputText event, on macOS and // Windows; on Linux, only the text comes while the element takes text // (TextCaret) with input methods on (InputMethod). Every key the system // tells the window of comes: a modifier on its own, a lone tap of Super // among them, the lock keys, and a key whose press the layout types no // Key for come with Key KeyUnknown, named by Code alone, and Mods holds // the modifier a press brings and not the one a release takes. Taking // one keeps it from the system, as Alt from the menu bar. InputKeyDown InputKind = iota + 1 InputKeyUp // InputText is text typed, or committed by an input method. InputText // InputCompose is the composition of an input method, with its caret // at rune Caret; an empty Text ends it. One the element leaves, the // input method gives up on macOS, as a terminal does the dead key ´ of // Option-E that it sent as Alt, so that the next key isn't composed // with it. InputCompose // InputCommand is an edit command of the menus, such as Copy of the // Edit menu: "copy", "cut", "paste", "pasteAndMatchStyle" (which // comes again as "paste" when the element doesn't take it), // "selectAll", "undo", "redo" or "delete", or one of the Format menu, // as Bold: "bold", "italic", "underline", "strikethrough", // "alignLeft", "alignCenter" or "alignRight". InputCommand // InputPointerDown and InputPointerUp report Button pressed or // released at X, Y, with Clicks the count of quick successive presses // (2 for a double click). Once the element takes an InputPointerDown, // the pointer's moves and its release come to it wherever they are, // and the release comes when the window loses the keyboard too, or // once a frame builds the element no more, as when the press moved it // into another container, or when the system cancels the press: those // releases are Canceled. InputPointerDown InputPointerUp // InputPointerMove reports the pointer at X, Y, with Button held, or // -1 when none is. InputPointerMove // InputScroll scrolls by DX, DY DIPs at X, Y; Precise marks // touchpads, which scroll by pixels rather than by lines. One the // element leaves scrolls the scroll containers around it. Momentum // marks scrolling that continues after the fingers leave a touchpad. InputScroll // InputSelect selects runes Start to End of the text an element // describes to assistive technology (Element.Access), as a screen // reader moves the selection of a text field of the app's own. InputSelect // InputZoom zooms by Scale at X, Y, as pinching a touchpad does: 2 // shows the content twice as large as it was, 0.5 half as large. // macOS, Linux on Wayland and browsers report pinches; Windows reports // them as scrolling with Ctrl held, so there a touchpad's scrolling // with Ctrl held comes as InputZoom too, and a mouse wheel's notches // as InputScroll with Ctrl in Mods. InputZoom // InputPointerLeave reports that the pointer left the surface or // stopped being over the element. It clears hover without ending a // pointer capture. InputPointerLeave )
Kinds of input.
type Key ¶
type Key uint16
Key identifies a key. Letter and digit keys follow the keyboard layout: KeyA is the key that types an a.
type KeyCode ¶
type KeyCode uint16
KeyCode is a key by its position on the keyboard, whatever the layout types and whichever system reports it (InputEvent.Code), with the sides of the modifiers told apart and every key of a full keyboard, those that Key has no name for too. Its values are USB HID usage IDs of the keyboard page (0x07), and its names the codes of UI Events' KeyboardEvent, Meta being Super here.
type Keyframe ¶
Keyframe is a value at At since a sequence starts. The first At must be zero, subsequent times strictly increase. Ease controls the segment arriving at this frame; nil means Linear.
type KeyframeOptions ¶
type KeyframeOptions struct {
// Run replays the sequence, or a changed one, when it changes: the
// first time through, it starts from the value shown, so that
// interrupting it does not jump.
Run uint64
// Repeat is how many more times the sequence plays after the first,
// as Motion's repeat: RepeatForever for ever. Alternate plays every
// other time backward.
Repeat int
Alternate bool
// Delay is how long the sequence holds its first value before it
// plays, and RepeatDelay how long it holds where it got to before it
// plays again.
Delay, RepeatDelay time.Duration
// NonMotion says that the sequence moves nothing on screen, as a
// pulsing opacity or a blur that settles: it still plays while the
// desktop asks for less motion, as Animation's NonMotion does.
NonMotion bool
}
KeyframeOptions controls playback.
type LineCap ¶
type LineCap uint8
LineCap is how a stroke ends where its subpath or a dash of it does.
type LineJoin ¶
type LineJoin uint8
LineJoin is how a stroke turns at a corner of its path.
const ( // RoundJoin turns a corner in an arc: the default. RoundJoin LineJoin = iota // MiterJoin turns a corner in a point, where the stroke's sides meet, // and bevels it where the point would be farther from the corner than // the miter limit (MiterLimit). MiterJoin // BevelJoin cuts a corner straight across. BevelJoin )
type LinearGradient ¶
type LinearGradient struct {
From, To Color
// Angle is the direction of the line, in degrees clockwise from
// upwards: 180 goes from top to bottom, 90 from left to right.
Angle float32
// Start and End place From and To along the line, from 0 to 1: the
// colors are solid before Start and after End. Both 0 mean 0 and 1.
Start, End float32
// Oklab mixes the colors in the Oklab color space, whose midpoints keep
// the colors' lightness and saturation, instead of in sRGB, as CSS's
// "in oklab" does.
Oklab bool
// Stops, unless empty, are the gradient's colors in place of From and
// To (and Start and End), at their places along the line from 0 to 1,
// in order:
//
// ui.LinearGradient{Angle: 90, Stops: []ui.GradientStop{{red, 0}, {yellow, 0.5}, {blue, 1}}}
Stops []GradientStop
}
LinearGradient blends colors along a line across a box, as CSS's linear-gradient does: two, From and To, or as many as its Stops.
e.LinearGradient(ui.LinearGradient{From: blue, To: yellow, Angle: 90, Oklab: true})
type ListRow ¶
ListRow gives a row its shared context, index, selection and list focus, and what the pointer does to it: content drawing the row's hover, press or a ripple from the pointer reads them here, as the row's Element would report them, and leaves the row the one element taking the click.
func (ListRow) Hovered ¶ added in v0.1.1
Hovered reports whether the pointer is over the row, as Element.Hovered does for the row: content asking for it is built again as the pointer comes and goes, while the row keeps taking the input.
func (ListRow) ListFocused ¶
func (ListRow) PointerPosition ¶ added in v0.1.1
PointerPosition returns the pointer's position relative to the row's box and whether it is over the row, as Element.PointerPosition does for the row: a ripple starts where Pressed first reports the press.
if row.Pressed() && app.ripple.Row != row.Index {
x, y, _ := row.PointerPosition()
app.ripple = Ripple{Row: row.Index, X: x, Y: y, At: time.Now()}
}
func (ListRow) Pressed ¶ added in v0.1.1
Pressed reports whether the pointer's primary button presses the row, as Element.Pressed does for the row, which takes the press: content asking for it draws the press without taking it, so a click on the row, or Tester.Click on its ListState.Label, still chooses it. In a list that does not choose its rows, asking makes the row take the press.
type ListState ¶
type ListState struct {
// Handle names this list independently of its per-pass node.
Handle
// Key returns an identity for the item row i shows, such as its ID:
// comparable, and unique among the rows. Without it, a row is its
// index. With it, the state of a row (focus, text being edited, …)
// follows its item, and the list keeps its place and its choice when
// rows are added or removed above them, as when older messages load.
Key func(row int) any
// KeepOffset keeps a list with a Key where it is scrolled as its rows
// move, rather than with the item at its top: for rows sorted again as
// they change, as a process monitor's, which the list would otherwise
// scroll along with the item at its top. The state of a row, the choice
// and the row Shift chooses from still follow their items.
KeepOffset bool
// FollowEnd starts the list at its end, and keeps the end in view as
// rows are added or grow while it shows it, as a chat or a log does:
// scrolling away from the end stops following it, and scrolling back
// to it follows again. Each layout reads it as it is then, so that one
// turned off in the frame a click opens a fold in the last row keeps
// the line clicked where it is; HoldPlace does that for one layout,
// leaving FollowEnd on.
FollowEnd bool
// FollowAnimation, when set, makes a list following its end glide to
// it as rows are added or grow, as the animation says (Smooth, a
// spring, or a curve), rather than show it at once: what is added
// comes up from below, as the chat apps scroll. A glide on its way
// goes on from where it is as more comes, and the user scrolling stops
// it. It shows the end at once where the desktop asks for less motion.
FollowAnimation *Animation
// Selected, when set, lets a click choose a row, as Up, Down, Home and
// End do while the list has the keyboard focus, and Page Up and Page
// Down on Linux and Windows: *Selected is the chosen row, -1 for none,
// which shows in the accent color. The list's Changed reports a new
// choice, and its Submitted a double click or Enter.
Selected *int
// Selection, when set, lets the user choose several rows, which it
// holds by their keys: a click chooses one, Cmd-click (Ctrl-click on
// Linux and Windows) adds a row or takes it out, and Shift-click
// chooses those from the row last chosen to it, as Shift with the keys
// that move the choice does; Cmd+A chooses all. On Linux and Windows,
// Ctrl with those keys moves without choosing, and Ctrl+Space adds the
// row there or takes it out. Selected, set as well, is the row last
// chosen, where the keys move from. A right-click on a row not chosen
// chooses it before its context menu opens, as Finder and Qt do, so
// the menu acts on it.
Selection Selector
// MenuKeepsSelection leaves the rows chosen as they are when a
// right-click opens a row's context menu: without it, a list with
// Selection chooses the row clicked unless it is chosen, and in a Table
// choosing cells the cell too, unless it is in the block. A list with
// Selected alone never chooses on a right-click.
MenuKeepsSelection bool
// Label returns the text of row i: typing the first letters of a
// row's text while the list has the keyboard focus chooses it, and
// assistive technology reads it as the row's name.
Label func(row int) string
// Header, when set, reports whether row i heads a section: the header
// of the section at the top of the list stays there while the rows of
// its section scroll under it, until the next header pushes it away.
// Give headers a background. Headers are not chosen.
Header func(row int) bool
// Reorder, when set, lets the user drag rows to another place in the
// list: the rows chosen, when the row dragged is one, else that row,
// which the list passes in order, and the row they go before, the
// number of rows for the end. Move them there: the list shows where
// they would go as they are dragged, and scrolls near its edges.
Reorder func(rows []int, to int)
// DragRows, when set, lets the user drag rows out of the list, as
// Element.Drag drags a value: the rows chosen, when the row dragged is
// one, else that row, which the list passes in order, drag the value
// DragRows returns, for Drop and DragOver elsewhere to take, as a
// folder in a list of files takes the files dropped on it. The list
// itself takes nothing and shows no place between the rows. Return nil
// for rows that do not drag. A list cannot both DragRows and Reorder.
DragRows func(rows []int) any
// DragSelect, with Selection, chooses rows as the pointer drags over
// them from the row it pressed: those from that row to the one under
// the pointer, as a Shift-click on it would, and with Cmd (Ctrl on
// Linux and Windows) held as the press began, those besides the rows
// chosen. Held near the list's top or bottom, or past them, the drag
// scrolls the list. A press on a row not chosen chooses it as the
// pointer goes down, as a click would, and a press on a row chosen
// waits for the release, so that a drag of the choice keeps it; this
// is so in a Table choosing cells too. A list cannot both DragSelect
// and Reorder (or DragRows).
DragSelect bool
// CellSelect, with Selection, makes a Table choose a block of cells:
// the rows chosen, times the columns from Cells.Anchor to Cells.Cursor
// in the order shown. A click on a cell chooses its row as a click on
// the row does and its column; a Shift-click extends the rows and the
// columns to it, and a Cmd-click adds its row or takes it out, keeping
// the columns. Dragging over cells chooses those it goes over, as
// DragSelect does the rows, scrolling sideways too. Left and Right
// move Cells.Cursor, and Shift with them extends the columns, except in
// an OutlineTable, where they open and close the rows as they do
// without CellSelect; the keys that move the rows leave one column,
// unless with Shift. The cells
// of the block show as a chosen row does, as do the RowHeader cells of
// whole rows chosen, and the one at Cells.Cursor in the row the keys
// move from has a border while the table has the focus. A RowHeader
// column chooses whole rows. A table cannot both CellSelect and
// Reorder (or DragRows).
CellSelect bool
// Cells are the columns of the block CellSelect chooses.
Cells ColumnRange
// CellsStyle paints the block of cells CellSelect chooses and the
// rows chosen instead of the accent, as a spreadsheet's: the chosen
// cells in a color of their own, the rest of their rows in a lighter
// one, and every other row striped. Its zero value keeps the accent.
CellsStyle CellsStyle
// Sort, when set, is the column a Table's rows are sorted by: a click
// on the header of a Sortable column sorts by it, ascending, and
// another reverses the order, which the header shows. Sort the rows as
// it says, when it changes. SortBy sorts by several columns, which
// Sort, set with it, follows.
Sort *SortOrder
// SortBy sorts a Table's rows by several columns, the first first. A
// click on a Sortable column's header sorts by it alone, as with Sort,
// and reverses it when it was first; a Cmd-click (Ctrl-click on Linux
// and Windows) or a Shift-click adds it after the others, ascending,
// another makes it descending, and a third takes it out. The headers
// show their direction and, when there are several, their place. It
// gets a new slice as it changes, so one the app kept stays as it was.
// When Sort is set too, the table keeps it the first of SortBy, the
// zero SortOrder when SortBy is empty, for the app to read the column
// that sorts first.
SortBy *[]SortOrder
// Columns keeps the order and the widths the user gave a Table's
// columns, by ID: restore it from saved settings, and save it as it
// changes.
Columns TableLayout
// RoundRows rounds the corners of a Table's chosen and hovered rows at
// the theme's Radius, as a List's are, rather than leaving them square
// from edge to edge.
RoundRows bool
// HeaderMenu, when set, gives a Table's header a context menu, built
// as ContextMenu's is: col is the index of the column clicked in the
// columns given to Table, not in the order the user moved them into,
// or -1 for the part of the header past the columns, as AppKit's
// clickedColumn. A menu built without items does not open.
HeaderMenu func(m *Menu, col int)
// HeaderCell, when set, is called as a Table builds each column's
// header cell, with the cell: what it builds goes in the cell after the
// title and the sort arrow, as a mark, and it may give the cell a
// tooltip or a card of its own. col is as HeaderMenu's.
HeaderCell func(cell Element, col int)
// CellMenu, when set, gives a Table's cells a context menu, built as
// ContextMenu's is, over the whole cell with its padding: row and col
// are as the cell builder receives them. A menu built without items
// does not open. A context menu of what a cell holds takes the
// right-click over it instead.
CellMenu func(m *Menu, row, col int)
// contains filtered or unexported fields
}
ListState is a List's place among its rows, how it behaves, and what it knows of the heights of its rows, kept in the app's state. Give each List a ListState of its own; set its fields before building the List.
func (*ListState) AtEnd ¶
AtEnd reports whether the list showed its end in the last frame, as Visible does its rows.
func (*ListState) CellSelected ¶
CellSelected reports whether the cell of row and col, as a Table's cell builder receives them, is chosen: its row is chosen and, in a table choosing cells (CellSelect), its column is in the block, or it is a RowHeader cell of a row chosen with every column. In a table that does not choose cells, every cell of a chosen row is. It is false before the list is first built. A cell builder can style what it holds with it:
ui.Table(c, &app.grid, cols, len(app.rows), func(row, col int) {
text := ui.Text(c, app.rows[row][col])
if app.grid.CellSelected(row, col) {
text.TextColor(c.Theme().AccentText)
}
})
func (*ListState) DragSelecting ¶
DragSelecting reports whether a drag choosing rows (DragSelect), or the cells of a Table (CellSelect), goes on: the pointer holds it. An app can put off work that follows the choice, as a sum of the cells chosen, until it ends: from the frame of the release on, it reports false.
func (*ListState) ExtendTo ¶
ExtendTo chooses the rows from the one Shift extends from to row, as a Shift-click on it does, and makes row the one the keys move from: for an app's own keys, as a key that extends the choice to the last row. Call it in the view, after the list is built. It does nothing without Selection.
func (*ListState) Focus ¶
Focus gives the list the keyboard focus and reports whether it was built in the current pass of c. A pending focus request can wait until a hidden list returns:
if app.focusFiles && app.files.Focus(c) {
app.focusFiles = false
}
Call it after building the list, or while building its rows.
func (*ListState) FocusWithin ¶
FocusWithin reports whether the list or one of its descendants has the keyboard focus, with the same lifetime as Focused. Row builders can use it before List returns, without saving an Element from an earlier frame.
func (*ListState) Focused ¶
Focused reports whether the List, Table or Outline using s has the keyboard focus. Call it from the view, after building the list or while building its rows. It returns false when s was not built in the current pass of c, including when the list is hidden.
func (*ListState) HoldPlace ¶
func (s *ListState) HoldPlace()
HoldPlace keeps the list where it is in the next layout rather than following its end, as a row opening a fold in the last message of a chat does, for the line clicked to stay under the pointer. FollowEnd stays as it is: the list follows its end again once it shows it, as when the user scrolls back to it. Call it from the view, in the frame that changes the rows.
func (*ListState) ScrollIntoView ¶
ScrollIntoView scrolls the list as little as shows row whole, as Element.ScrollIntoView does an element.
func (*ListState) ScrollTo ¶
ScrollTo scrolls the list to show row at align: Start shows it at the top, Center in the middle and End at the bottom. Call it from the view: the list scrolls as the frame is laid out, to where the row is once it is measured.
func (*ListState) ScrollToEnd ¶
func (s *ListState) ScrollToEnd()
ScrollToEnd scrolls the list to its end, where FollowEnd follows it again.
func (*ListState) SelectColumns ¶
SelectColumns chooses every row of a Table choosing cells (CellSelect) and the columns from the one whose ID is from to the one whose ID is to, which becomes Cells.Cursor. Call it in the view, after the table is built.
func (*ListState) SelectedColumns ¶
SelectedColumns returns the IDs of the columns of the block of cells a Table chooses (CellSelect), in the order shown in the last frame, without RowHeader columns.
func (*ListState) Shortcut ¶
Shortcut reports whether mods+key was pressed while the list or one of its descendants had the focus, as Element.Shortcut does. Call it after building the list, or while building its rows. A list not built in the current pass of c registers and handles no shortcuts.
type Mask ¶
type Mask struct {
// Image is what the layer masks by: the alpha of a LinearGradient, a
// RadialGradient or a ConicGradient across Box, whatever its colors.
// A gradient of one color, as LinearGradient{From: black, To: black},
// shows all of Box.
Image MaskImage
// Composite is how the layer goes with those after it in the list,
// which are under it: MaskAdd, by default, shows what either shows.
// The last layer's is not used.
Composite MaskComposite
// Box is the box the image lies across, nothing of the layer showing
// outside it: the element's border box by default, or its padding box
// or its content box.
Box MaskBox
}
Mask is a layer of an element's mask (Element.Masks), as one image of CSS's mask-image, with its mask-composite and its mask-origin and mask-clip.
type MaskBox ¶
type MaskBox uint8
MaskBox is the box a layer of a mask lies across (Mask.Box), as CSS's mask-origin and mask-clip.
type MaskComposite ¶
type MaskComposite uint8
MaskComposite is how a layer of a mask goes with the layers under it, as CSS's mask-composite: each point shows as much as the result there.
const ( // MaskAdd shows the layer over those under it: what either shows. MaskAdd MaskComposite = iota // MaskSubtract shows the layer where those under it do not. MaskSubtract // MaskIntersect shows the layer where those under it show too. MaskIntersect // MaskExclude shows the layer and those under it where the other does // not: what one of them shows, but not both. MaskExclude )
type MaskImage ¶
type MaskImage interface {
// contains filtered or unexported methods
}
MaskImage is what a layer of a mask masks by: a LinearGradient, a RadialGradient or a ConicGradient.
type Material ¶
type Material interface {
// PaintMaterial paints the material over box, rounded by radii, in
// DIPs, under the element's border and children.
PaintMaterial(p *Painter, box Rect, radii [4]float32)
}
Material is what Element.Material fills an element with in place of a background: a look a package paints, as the glass plugin's Liquid Glass (github.com/caelyreth/evil-mygo/plugins/glass).
type MaterialBuilder ¶
MaterialBuilder builds a material using a checked element.
type Menu ¶
type Menu struct {
// contains filtered or unexported fields
}
Menu is a menu being built, by the function given to ContextMenu, PopoverMenu, Element.Menu or PopoverMenuButton. Its items show in the order they are added.
func (*Menu) EditItems ¶
func (m *Menu) EditItems()
EditItems adds the editing items of the text the menu opened on, as its menu has them without ContextMenu: Copy and Select All for selectable text, the platform's text field items for a text input. Choosing one does its command on the text, without reaching the menu's function. An element within text, as a link in a paragraph, opens its menu on that text. It adds nothing to a menu that opened on no text.
func (*Menu) MaxWidth ¶ added in v0.1.1
MaxWidth keeps the menu, as PopoverMenu and PopoverMenuButton draw it, at most w DIPs wide: labels, subtitles and Trailing texts too long for it end with an ellipsis, while shortcuts, icons and marks keep their room. Its submenus take the same width unless their function sets one of its own; 0 lifts it, and a drawn menu is never narrower than its least width, 45 units of the theme's Spacing. Assistive technology, Tester.Menu and the letters typed to go to an item still see each label whole, and a Tooltip can show it to the pointer. The system's menus take no width from it.
ui.PopoverMenuButton(c, "Recent", func(m *ui.Menu) {
m.MaxWidth(320)
for _, f := range app.recent {
if m.Item(f.Path).ID(f.Path).Tooltip(f.Path).Chosen() {
app.open(f)
}
}
})
type MenuIcon ¶
MenuIcon is the image of a menu item, as mygo.NewMenuIcon makes it of a PNG image, and mygo.NewMenuIconSVG of an SVG document.
type MenuItem ¶
type MenuItem struct {
// contains filtered or unexported fields
}
MenuItem is an item of a Menu. Its methods set it up and return it, for chaining, and Chosen reports the choice.
func (*MenuItem) Checked ¶
Checked shows a check mark by the item when on is true, as for a setting that choosing the item toggles.
func (*MenuItem) Chosen ¶
Chosen reports whether the item was chosen, in the frame after the user chose it: the item with the ID of the one chosen, when it had one (ID), else the one at its place with its label.
func (*MenuItem) Content ¶ added in v0.1.1
func (it *MenuItem) Content(fn func(content MenuItemContent)) *MenuItem
Content builds what the item shows in place of its label and subtitle, as PopoverMenu and PopoverMenuButton draw it: fn builds the children of a column between the item's mark and icon and its Trailing text and shortcut, as the item shows, highlighted or not (MenuItemContent). Text in it takes the color of the item's label. The item keeps its label: assistive technology reads it as the item's name, the letters typed go to it, and the system's menus show it, without the content.
m.Item("Download").Trailing("40%").Content(func(x ui.MenuItemContent) {
ui.Text(x.Context, "Download")
ui.Progress(x.Context, app.progress)
})
The content is part of the item, which keeps the pointer and the keys of the menu: a press on it chooses the item, closing the menu, and the pointer highlights it. A control in it takes its own presses, as a text input that a click gives the focus to, as a filter of the items after it: it keeps the focus as the pointer moves over its item, and has the keys it handles, the text typed with Space, and Enter, Home and End for a text input. Up and Down still move the highlight, giving the menu the focus back, the pointer moving onto another item does too, and Escape closes the menu. The item stays one the keys and the pointer stop at, and Enter on it, or a press beside the control, chooses it; a menu of one's own (MenuBase, ContextMenuBase) can put such a field outside its items.
func (*MenuItem) Danger ¶ added in v0.1.1
Danger shows the item in the theme's Danger color, as one that deletes or discards: its label, and its mark and template icon. Highlighted, it shows the theme's highlight, as the other items do, with its label in the Danger color where that is legible on the highlight, else in the highlight's text color (Theme.AccentText). The color alone tells no one using assistive technology: let the label say what the item does, as "Delete…". PopoverMenu draws it so; the system's menus show the item as the others.
if m.Item("Delete…").Danger().Chosen() {
app.confirmDelete()
}
func (*MenuItem) Highlighted ¶ added in v0.1.1
Highlighted reports whether the item is highlighted in the menu drawn in the window (PopoverMenu, PopoverMenuButton), as the pointer or the keys are on it or on an item of the submenu it opens: the menu's function can show, as it builds, what goes with the item the user is on, as a preview of a theme:
for _, th := range themes {
item := m.Item(th.Name).ID(th.Name)
if item.Highlighted() {
app.preview = th
}
if item.Chosen() {
app.theme = th
}
}
The function sees the highlight of the menu's last pass, and builds again when it moves; in Content, it is the item's own as it builds. Call ID first, and give the items IDs when the items the function builds change with the highlight. It reports false for the system's menus, which tell no highlight, and as an item is chosen.
func (*MenuItem) ID ¶ added in v0.1.1
ID gives the item an identity of its own, which Chosen and Highlighted match instead of the item's place and label: a label that changes while the menu shows, as a time or a count, or items before it that come and go, then keep the choice on the item. Give the items of a menu and its submenus different IDs; "" is none. In a drawn menu, ID also keys the item's row, whose highlight then stays on it as items around it come and go.
if m.Item(fmt.Sprintf("Sync %d Files", app.pending)).ID("sync").Chosen() {
app.sync()
}
func (*MenuItem) Icon ¶
Icon shows an image beside the item's label, one mygo.NewMenuIcon or mygo.NewMenuIconSVG made: make each once, not as the menu builds, and give it to the items that show it. A template image takes the color of the item's text, or its IconColor in the menus MyGo draws. nil shows none. The system's menus show it as package mygo's items do (see NewMenuIcon), and browsers show none; PopoverMenu draws it on every platform.
if m.Item("Archive").Icon(archiveIcon).Chosen() {
app.archive(msg)
}
func (*MenuItem) IconColor ¶ added in v0.1.1
IconColor draws the item's template icon (Icon) in c rather than in the color of its text, as a red trash can by a Delete item, or a status's color by its name. An icon in its own colors keeps them. While the item is highlighted, its icon takes the highlight's text color, as its label does, and a disabled item's is dimmed as its label is.
Only the menus MyGo draws show it: PopoverMenu's and PopoverMenuButton's, and ContextMenu's and Menu's in a window that draws its menus (PopoverMenus). The system's menus tint template icons themselves, in the color of their text, and leave it out.
if m.Item("Delete").Icon(trashIcon).IconColor(t.Danger).Chosen() {
app.delete(msg)
}
func (*MenuItem) Radio ¶
Radio shows the item as one of a group choosing one setting, as the one chosen when on is true:
for _, by := range []string{"Name", "Date", "Size"} {
if m.Item(by).Radio(app.sort == by).Chosen() {
app.sort = by
}
}
Chosen reports the choice; the view marks the item chosen as it builds the menu again.
func (*MenuItem) Shortcut ¶
Shortcut shows a key with modifiers by the item, as the shortcut that does the same; the view handles the key itself, as with Context.Shortcut.
func (*MenuItem) Subtitle ¶ added in v0.1.1
Subtitle shows s on a second, smaller line under the item's label, as package mygo's MenuItem.Subtitle does: PopoverMenu draws it so on every platform, in the color of the shortcuts, and the system's menus show it as they show the subtitles of package mygo's items, under the label on macOS 14 and in browsers, after it elsewhere ("Label — Subtitle"). Assistive technology reads it as the item's description, before its Tooltip.
m.Item("Back Up Now").Subtitle("Last backup: 3 minutes ago")
func (*MenuItem) Tooltip ¶
Tooltip shows s as the pointer rests on the item, as Element.Tooltip does, to say what it does. The system's menus show it on macOS and Linux, as package mygo's items' ToolTip, and those of Windows and browsers show none; PopoverMenu shows it on every platform.
m.Item("Run").Shortcut(ui.Cmd, ui.KeyEnter).Tooltip("Runs the query under the caret")
func (*MenuItem) Trailing ¶ added in v0.1.1
Trailing shows s at the end of the item, before its shortcut, in the color of the shortcuts, as a value beside a name: a file's size, a count. Assistive technology reads it as part of the item's description. PopoverMenu draws it; the system's menus show the label alone.
m.Item("Image.png").Trailing("2.4 MB")
type MenuItemContent ¶ added in v0.1.1
type MenuItemContent struct {
Context *Context
// Highlighted is set while the pointer or the keys are on the item,
// Disabled while it cannot be chosen.
Highlighted, Disabled bool
// Text is the color of the item's label as it shows, Muted that of its
// shortcut and Trailing text.
Text, Muted Color
}
MenuItemContent is what an item's Content builds with: the context, and how the item shows.
type MenuParts ¶
type MenuParts struct {
Trigger Element
// contains filtered or unexported fields
}
MenuParts contains checked handles for the parts of a custom widget.
func ContextMenuBase ¶
ContextMenuBase gives target a context menu without a look, which shows while *open is true, as MenuBase's: it opens where target is clicked with the secondary button, or Control-clicked on macOS, and, while target or an element inside it has the focus, below it when the menu key or Shift+F10 is pressed. Build it in Popup, as MenuBase's; it has the same keys, and assistive technology sees it so. PopoverMenu draws its menu with these parts, in the theme's look.
m := ui.ContextMenuBase(c, row, &app.rowMenu)
m.Popup(func(panel ui.Element) { ... })
func MenuBase ¶
MenuBase creates a menu button without a look, whose menu shows while *open is true: a button that takes the focus and opens the menu as the pointer goes down on it, or for Enter, Space, Up or Down while it has the focus, and closes it when pressed again. Give the trigger children, and build the menu in Popup with Item, CheckItem, RadioItem and SubmenuItem, and the submenus with Submenu; an item's Clicked reports its choice, which closes the menu:
m := ui.MenuBase(c, &app.menuOpen)
m.Trigger.Padding(6).Radius(6).Children(func() { ui.Icon(c, dots) })
m.Popup(func(panel ui.Element) {
panel.Padding(4).Radius(8).Background(t.Background).Border(1, t.Border)
item := m.Item().Padding(6, 10).Radius(4)
if item.Highlighted() {
item.Background(t.Accent).TextColor(t.AccentText)
}
item.Children(func() { ui.Text(c, "Duplicate") })
if item.Clicked() {
app.duplicate()
}
})
The menu has the keys of PopoverMenu's: it takes the focus as it opens, on its first item when the keyboard opened it, and gives it back as it closes; Up and Down move the highlight among its items, past those disabled, as do Home, End and typing the first letters of an item; Right opens a submenu and Left closes it, the other way round right to left (Direction); Enter and Space choose an item, Escape closes the submenu on top, and Tab and a press outside the menu close it. The pointer highlights the item it moves onto, opening its submenu. Assistive technology sees a menu button, expanded while its menu shows, and a menu of items, check box items and radio items. PopoverMenuButton draws its menu with these parts, in the theme's look.
func (MenuParts) CheckItem ¶
CheckItem creates an item, as Item does, that assistive technology sees as a check box item, checked while checked is set: flip what it shows when it is Clicked.
func (MenuParts) Group ¶
Group creates a group of the items that fn builds in the menu being built, a row that fn styles: the keys take it as one item, Up and Down moving onto it at its item checked, else its first, and Left and Right move among its items, round from the last to the first, the other way round right to left (Direction), instead of opening and closing submenus. Its items show, are highlighted by the pointer and are chosen as the others are; a row of radio items that KeepOpen, as a theme's Light, Dark and System, switches without closing the menu:
m.Group(func(row ui.Element) {
row.Gap(4).Label("Theme")
for _, th := range []string{"Light", "Dark", "System"} {
item := m.RadioItem(app.theme == th).KeepOpen().Padding(4, 8)
item.Children(func() { ui.Text(c, th) })
if item.Clicked() {
app.theme = th
}
}
})
Assistive technology sees a group, named by its Label, of the items in it, which it counts on their own. It returns the group.
func (MenuParts) Item ¶
Item creates an item of the menu being built in Popup or Submenu: a row that is Highlighted while the pointer or the keys are on it, and whose Clicked reports its choice, by the pointer, Enter or Space, which closes the menu, unless KeepOpen. Give it children; Disabled leaves it out of the keys' way and of the pointer's. Assistive technology sees a menu item.
func (MenuParts) Popup ¶
Popup shows the menu while it is open: below the trigger of a menu button, lined up with its start, or above it where the window has no room, and a context menu after where it opened, or before it, as from a corner. fn styles the panel, a column that scrolls the items past the room the window has, and builds the items in it. It returns the panel, or nil while the menu is closed.
func (MenuParts) RadioItem ¶
RadioItem creates an item, as Item does, that assistive technology sees as a radio item, the one chosen of its group while selected is set.
func (MenuParts) Submenu ¶
Submenu builds the submenu of item, a SubmenuItem of the menu being built, while it shows: fn styles its panel, after the item and lined up with it, and builds its items, as Popup's.
func (MenuParts) SubmenuItem ¶
SubmenuItem creates an item, as Item does, that opens a submenu instead of being chosen: as the pointer moves onto it or clicks it, and for Right, Enter or Space while it is highlighted. Build the submenu with Submenu. Assistive technology sees a menu item that expands, expanded while its submenu shows.
type MenuPresentation ¶
type MenuPresentation uint8
MenuPresentation is how a window shows its popup menus (Context.SetMenuPresentation): the system's, or drawn in the window.
const ( // SystemMenus shows popup menus as the system's, as ContextMenu and // Menu do by default. SystemMenus MenuPresentation = iota // PopoverMenus draws popup menus in the window with the theme's look, // as PopoverMenu and PopoverMenuButton draw theirs. PopoverMenus )
type MeterLevels ¶
type MeterLevels struct {
Warning, Critical float64
}
MeterLevels are the levels of a Meter from which its value shows it is worse: the theme's Warning color from Warning, its Danger color from Critical. A Critical below Warning makes low values the bad ones, as a battery's. Their zero value shows the theme's Success color throughout.
type Motion ¶
type Motion struct {
// X and Y move it by as many DIPs, and XPercent and YPercent by as
// many percent of its own width and height, as TranslatePercent does.
X, Y float32
XPercent, YPercent float32
// Opacity is how opaque it is there: 0, as by default, is
// transparent, and 1 opaque.
Opacity float32
// Collapse makes it nothing along its parent's direction: no height in
// a column, no width in a row. Its content keeps its layout, clipped.
Collapse bool
// Scale is how large it is there, around its TransformOrigin: 0.9 a
// tenth smaller; 0, as by default, keeps it at its size, as 1 does.
// Rotate turns it by as many degrees clockwise.
Scale, Rotate float32
// Blur blurs it there by as many DIPs, as Element.Blur does: text or
// an icon crossing over to another through a blur of 4 or so.
Blur float32
// Flip, for an element attached to another (AttachTo), mirrors X and
// XPercent where the layout put it across its target from where it
// was asked to go, and Y and YPercent where it put it the other way
// down (AttachedAnchors), from the frame it appears: a menu asked
// below its button, coming down from Y: -8, comes up from 8 where it
// opens above it, as its Exit goes.
Flip bool
}
Motion is where an element appearing comes from, or where one going goes, from its place in the layout.
type NativeGlassMaterial ¶
type NativeGlassMaterial interface {
Material
// NativeGlass asks for the system's glass, or reports false for the
// material's own drawing.
NativeGlass() (NativeGlassSpec, bool)
}
NativeGlassMaterial is a Material drawn by the system where it has Liquid Glass (macOS 26 and later), instead of by the renderer: the material leaves a hole in the frame and the system's glass view, under it, shows what is under the surface, as a ui.WebView's page. The frame under the material is what the glass samples, not the elements the frame painted.
type NativeGlassSpec ¶
NativeGlassSpec is how a NativeGlassMaterial asks for the system's glass: its style (0 regular, 1 clear) and tint, A 0 for none.
type NativeWebView ¶
NativeWebView is a web view a window made for its content to show, as *mygo.WebView, of mygo.Window.NewWebView.
type Orientation ¶
type Orientation uint8
Orientation says which arrows move the focus in a FocusGroup: Left and Right (Horizontal), Up and Down (Vertical), or all four (Horizontal|Vertical).
const ( Horizontal Orientation = 1 << iota Vertical )
type OutlineRow ¶
type OutlineRow struct {
// Depth is how deep the row's item is: 0 at the top. Branch tells
// that it has children, and Open that they show.
Depth int
Branch, Open bool
// contains filtered or unexported fields
}
OutlineRow is a row of an outline as its Prefix builds it, while it builds it.
func (OutlineRow) Arrow ¶
func (r OutlineRow) Arrow() Element
Arrow creates the row's arrow without a look: a box that opens or closes the item when clicked, with all inside it with Option (Alt), leaving the keyboard focus where it is. Size it and draw it from Open. Of an item without children, it is a box that does nothing, which keeps the rows' content in line.
type OutlineState ¶
type OutlineState[K comparable] struct { // List is the state of the rows: their place, and how they are chosen, // as a List's. Its Key is the rows' items; a Selection takes them, of // type K. List ListState // Open holds the items showing their children. Open Selection[K] // Indent is the width in DIPs each level adds before a row's arrow, // without a Prefix, the theme's Space(4) when zero. It must not be // negative. Indent float32 // Prefix, when set, builds the start of each row in place of the // outline's indentation and arrow, before what row builds, for rows of // a look of your own: r tells how deep the row's item is and whether // it is open, and Arrow makes the element opening and closing it. An // Outline's rows then have neither padding nor a gap, and center // what they hold; an OutlineTable's first cells keep their padding. Prefix func(r OutlineRow) // contains filtered or unexported fields }
OutlineState is the state of an Outline or an OutlineTable: its rows, as a List's, and the items that are open, showing their children. The rows' keys are the items, of type K, so that their place, choice and state follow them as items open and close above them.
type app struct {
files ui.OutlineState[string] // paths
file int
}
app.files.List.Selected = &app.file
func (*OutlineState[K]) Depth ¶
func (s *OutlineState[K]) Depth(row int) int
Depth returns how deep the item of row i is: 0 for the items at the top.
func (*OutlineState[K]) Item ¶
func (s *OutlineState[K]) Item(row int) K
Item returns the item row i shows, in the last frame.
func (*OutlineState[K]) Rows ¶
func (s *OutlineState[K]) Rows() int
Rows returns how many rows the outline shows: its items at the top, and the children of those open, in the last frame.
type Painter ¶
type Painter struct {
// contains filtered or unexported fields
}
Painter draws an element's own content in Element.Draw and DrawOver callbacks, in DIPs relative to the window.
func (*Painter) Accelerated ¶
Accelerated reports whether the frame draws on a GPU: false where it draws in memory (with MYGO_GPU=0, without a GPU MyGo can draw with, as in most virtual machines, and in Render and tests) and where the GPU's renderer draws on the CPU (Direct3D's WARP, Mesa's llvmpipe, browsers' SwiftShader). A drawing that costs too much there, as a shader covering much of the window (package shader runs one pixel by pixel on the CPU), can draw less, or nothing. Should the answer change, as when the GPU goes away or comes back, the window is painted again.
func (*Painter) After ¶
After asks for the element to be painted again after d, for a drawing that changes then, as a spinner's next step: unless something else changed meanwhile, that frame paints the elements of this one again without building the view. An element out of view is not painted, so it asks for none.
func (*Painter) AnimationFrame ¶
func (p *Painter) AnimationFrame()
AnimationFrame asks for the element to be painted again as soon as the display can show it, for a drawing that moves with Now while the layout stays, as a spinner's: unless something else changed meanwhile, the next frame paints the elements of this one again without building the view. Call it in every frame while the drawing moves; an element out of view is not painted, so it asks for none.
func (*Painter) AnimationFrameRate ¶
AnimationFrameRate is AnimationFrame for a drawing that looks as smooth at fps frames a second as at the display's rate, as a record turning, a slow wave or a level meter: the window paints it again as often, rather than at each of the display's refreshes, 120 a second on ProMotion and many others, and has the display refresh as often where it can (macOS), for less power. The rate rounds up to one the display shows evenly, a whole number of its refreshes a frame: 60, 40 or 30 a second of a 120 Hz display's, 60 or 30 of a 60 Hz one's. The window draws at the fastest anything in it asks for: at the display's while another drawing asks for AnimationFrame or the view animates.
func (*Painter) ClipPath ¶
ClipPath restricts what fn draws to the inside of a path, by its FillRule (as SVG's clip-rule), its edges smoothed: a drawing cut to a polygon or to any outline, as CSS's and SVG's clip-path. Clips nest with those of Clip, and turn with a transform:
star := ui.MustParsePath("M50 0 L61 35 L98 35 L68 57 L79 91 L50 70 L21 91 L32 57 L2 35 L39 35 Z")
p.ClipPath(star, func() {
p.FillGradient(r, ui.LinearGradient{From: gold, To: orange, Angle: 135}, 0)
})
The clip is a mask of the path's coverage, made once for each shape and size it is drawn at.
func (*Painter) Effect ¶
func (p *Painter) Effect(fx *scene.Effect, r Rect, radii [4]float32, blur float32, params [5][4]float32)
Effect paints the rectangle r rounded by radii, in DIPs, with an effect: shaders the renderers draw it with (see scene.Effect), which only this module's packages define, as the official plugins do. params are the effect's own, in device pixels (Scale), and blur the standard deviation of the blur of its backdrop, in device pixels, for an effect reading one.
func (*Painter) EffectBackdrop ¶
func (p *Painter) EffectBackdrop(r Rect, blur float32, inset Point) EffectBackdrop
EffectBackdrop returns where the backdrop of an effect over r, in DIPs, blurred by blur pixels, lies, its points from inset, in pixels from the corner of r on the pixel grid: what the renderers read for it, the same for every renderer.
func (*Painter) EffectColor ¶
EffectColor returns c as a parameter of an effect: straight RGBA from 0 to 1, its sRGB value, and wide, its color outside the sRGB gamut in extended sRGB, which an effect's wide-gamut shader can take where e.wide tells that the target keeps it (wide is the sRGB value for a color inside the gamut). Like a color an element paints, it has the frame drawn in a wide gamut where the window shows one.
func (*Painter) EffectWords ¶
EffectWords returns n words, zero, for the uniforms of an effect this frame paints (ShaderInput), which last until the frame is drawn.
func (*Painter) FillConicGradient ¶
func (p *Painter) FillConicGradient(r Rect, g ConicGradient, radius float32)
FillConicGradient fills a rounded rectangle with a conic gradient around it.
func (*Painter) FillGradient ¶
func (p *Painter) FillGradient(r Rect, g LinearGradient, radius float32)
FillGradient paints a rounded rectangle with a gradient.
func (*Painter) FillPathConicGradient ¶
func (p *Painter) FillPathConicGradient(path *Path, g ConicGradient)
FillPathConicGradient fills a path with a conic gradient around its bounds.
func (*Painter) FillPathGradient ¶
func (p *Painter) FillPathGradient(path *Path, g LinearGradient)
FillPathGradient fills a path with a gradient across its bounds, as the area under a chart's line.
func (*Painter) FillRadialGradient ¶
func (p *Painter) FillRadialGradient(r Rect, g RadialGradient, radius float32)
FillRadialGradient fills a rounded rectangle with a radial gradient, its colors spreading out from a point of it.
func (*Painter) FillRadii ¶
FillRadii paints a rounded rectangle whose corners have radii of their own, clockwise from the top left, as Element.Radius does.
func (*Painter) FocusRing ¶
FocusRing draws the ring that shows the keyboard focus around r, whose corners are rounded by radius, as the theme draws it: FocusRingWidth wide, FocusRingOffset outside r, in Focus.
func (*Painter) Glyphs ¶
Glyphs draws glyphs that Shape made, from x, on the baseline at y, in color c.
func (*Painter) Hole ¶
Hole leaves a rounded hole in the frame, through which what is under the window's surface shows: the page of a ui.WebView, or a system's glass view that a NativeGlassMaterial places. Its own ink, as a material's, paints nothing there.
func (*Painter) Image ¶
func (p *Painter) Image(src ImageSource, r Rect, fit Fit)
Image draws a bitmap, or an SVG in its own colors (with the theme's text color for its currentColor), scaled to fit r.
func (*Painter) ImageRegion ¶
func (p *Painter) ImageRegion(b *Bitmap, src, dst Rect, o ImageOptions)
ImageRegion draws the part src of bitmap b, in its pixels (empty for all of it), stretched into dst, as Image draws a bitmap (pixelated if it is), unless dst is outside what the painter shows. Nothing of the bitmap around src shows, so that the parts of a bitmap holding many, as the icons of a sheet or the frames of an animation, draw on their own. Under a transform (Painter.Transform), dst is where it is, not snapped to pixels, so that a part moving through a zoomed view glides:
p.ImageRegion(icons, ui.Rect{X: 32, W: 16, H: 16}, box, ui.ImageOptions{})
func (*Painter) Line ¶
Line paints a straight horizontal or vertical line between two points, width DIPs thick. It draws no other angle: between points that differ in both x and y, it paints the longer of the top and left edges of the box between them, the top if they are as long. StrokePolyline draws a slanted line.
func (*Painter) MeasureText ¶
MeasureText returns the size spans of text take as Painter.RichText draws them, wrapping lines at width DIPs (none for 0).
func (*Painter) NativeGlassSupported ¶
NativeGlassSupported reports whether the window's surface draws the system's glass, as macOS 26's NSGlassEffectView does.
func (*Painter) Now ¶
Now returns the time of the frame being painted, which drawings that move compute from.
func (*Painter) Preferences ¶
func (p *Painter) Preferences() Preferences
Preferences returns the settings of the desktop that materials follow, as Context.Preferences does: a material that reduces its translucency or strengthens its contrast reads them here.
func (*Painter) RichText ¶
RichText draws spans of text as RichText shows them, with its top-left corner at (x, y), wrapping lines at width DIPs (none for 0), and returns the size it takes. What the spans leave zero takes the theme's font, FontSize and Text color:
w, _ := p.MeasureText(0, label) p.RichText(r.X+(r.W-w)/2, r.Y, 0, label)
func (*Painter) Scale ¶
Scale returns how many device pixels a DIP is, for drawing that lines up with the pixels of the display.
func (*Painter) Scrollbar ¶
func (p *Painter) Scrollbar(s Scrollbar, st ScrollbarState)
Scrollbar paints the thumb of a scroll bar, as a scroll container's, on no track, if it has anywhere to scroll.
func (*Painter) ShaderEffect ¶
ShaderEffect paints the rectangle r rounded by radius, in DIPs, with fx, the effect of a shader of package ui/shader (scene.Effect.Shader), reading in. Only this module's packages make such effects.
func (*Painter) ShaderFill ¶
func (p *Painter) ShaderFill(fx *scene.Effect, box Rect, in ShaderInput, fn func())
ShaderFill paints the text, paths and icons that fn paints with fx, the effect of a shader of package ui/shader, in place of their colors: each pixel the shader's color times the shape's coverage. box, in DIPs, is the box the shader fills, whose top left corner its positions start from. Glyphs of color, as emoji, keep their colors, and what fn paints besides, as rectangles and images, paints as it would. fx reads in. Only this module's packages make such effects.
func (*Painter) Shadow ¶
Shadow paints the box shadow of a rounded rectangle as Element.Shadow does: offset by x and y, blurred by blur and grown by spread DIPs, and only outside the rectangle, so that it does not show through what is drawn there.
func (*Painter) Stroke ¶
Stroke paints the outline of a rounded rectangle, width DIPs wide inside its edge.
func (*Painter) StrokeDashed ¶
StrokeDashed paints the outline of a rounded rectangle in dashes, as a dashed border.
func (*Painter) StrokePath ¶
StrokePath draws the outline of a path, width DIPs wide, with the path's caps, joins and dashes (Path.Cap, Path.Join, Path.Dash): round and whole unless it sets them.
func (*Painter) StrokePathConicGradient ¶
func (p *Painter) StrokePathConicGradient(path *Path, width float32, g ConicGradient)
StrokePathConicGradient draws the outline of a path as StrokePath does, in a conic gradient around its bounds.
func (*Painter) StrokePathGradient ¶
func (p *Painter) StrokePathGradient(path *Path, width float32, g LinearGradient)
StrokePathGradient draws the outline of a path as StrokePath does, in a gradient across its bounds.
func (*Painter) StrokePolyline ¶
StrokePolyline draws a line through points in DIPs, width DIPs wide, with round joins and caps, as StrokePath draws a path of straight lines: a NaN or infinite point breaks the line there, and a point alone draws nothing. It suits lines that change every frame, as live charts: on a GPU, an opaque line draws each segment as a rounded rectangle instead of rasterizing a mask of the whole line, so that its edges can look a little bolder where segments overlap. Translucent lines draw as StrokePath's, which keeps overlaps from showing darker, unless they are one segment, which has nothing to overlap: many lines of one, as a hatching, each stroked alone, cost no masks.
func (*Painter) TextLayout ¶
func (p *Painter) TextLayout(layout *TextLayout, x, y float32, color Color)
TextLayout paints a retained layout at (x,y) in DIPs, with color as the default foreground. Span colors and decorations paint as RichText does.
func (*Painter) TextLine ¶
TextLine paints the glyphs of the first line of l, a layout of this module's text system that only its packages make, as package ui/editor does, from x, on the baseline at y, each in the color color returns for the rune its cluster starts at. Glyphs outside the painter's clip are left out.
func (*Painter) Theme ¶
Theme returns the theme of the element being painted: that of the Themed around it, else the window's.
func (*Painter) Transform ¶
Transform transforms what fn draws by t around the point (ox, oy), which t leaves where it is, after the painter's own transforms: it nests. A view that pans and zooms, as a map or a diagram, draws its content through one, and a dial turns its needle around its center with another:
view := ui.Translation(-panX, -panY).Then(ui.Scaling(zoom, zoom))
p.Transform(view, r.X, r.Y, func() {
drawDiagram(p)
p.Transform(ui.Rotation(angle), cx, cy, func() { p.Line(cx, cy, cx, cy-40, 2, red) })
})
Clips made in fn turn with what it draws, and what the transform moves out of view is culled as usual. Input is not transformed: the pointer comes in the element's coordinates, which the app maps to its content itself.
func (*Painter) Visible ¶
Visible returns what the painter's clip leaves of the window, in DIPs: the part of an element's box that shows inside the scroll containers and clips around it, as an element taller than the window, showing a long document, paints only what falls in it. It is in the coordinates the painter draws in: under a transform, an element's or the painter's, the clip taken back through it, so an element scaled up sees as much less of itself as shows.
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path is a vector shape, in DIPs, for Painter.FillPath and StrokePath: icons, check marks, charts.
func MustParsePath ¶
MustParsePath is ParsePath for path data that is part of the program: it panics when the data is in error.
func ParsePath ¶
ParsePath makes a path of SVG path data, as the d attribute of an SVG path element holds it, in its units as DIPs: an icon's outline to fill with a gradient, stroke, draw in with Trim or dash with Dash, as any path a Painter draws.
check := ui.MustParsePath("M4 12l5 5L20 6")
p.Transform(ui.Scaling(2, 2), r.X, r.Y, func() {
p.StrokePath(check.Trim(0, drawn), 2, c.Theme().Accent)
})
Its arcs and quadratic curves become cubic curves. Path data in error makes the path up to the error, as SVG draws it, which ParsePath returns with the error.
func (*Path) Bounds ¶
Bounds returns the smallest box holding the path's points and the control points of its curves, in DIPs: the box of a circle (Circle), of lines, and of curves whose control points lie on it; others may fit in less. Empty paths have an empty box.
func (*Path) Cap ¶
Cap sets how a Painter strokes the ends of the path's open subpaths and of its dashes, round by default, as SVG's stroke-linecap, and returns the path.
func (*Path) Contains ¶
Contains reports whether the point (x, y) is inside the path, in the coordinates of its points, as a Painter fills it (FillRule): Canvas's isPointInPath. Its subpaths close, as filling closes them, and Trim keeps what it fills; its curves are flattened as a Painter flattens them at a scale of 4. A view tells with it which of a pie's segments, a map's regions or a ring's band a press is in, in its own handler or in an element's HitTest.
func (*Path) CubeTo ¶
CubeTo draws a cubic Bézier curve to (x, y) with control points (c1x, c1y) and (c2x, c2y).
func (*Path) Dash ¶
Dash sets a Painter to stroke the path in dashes, as SVG's stroke-dasharray and stroke-dashoffset, and returns the path. lengths are those of the dashes and the gaps between them in turn, in DIPs, repeated along the path, and twice over when there is an odd number of them; each subpath starts them anew, offset DIPs into them, and a dash through the start of a closed one turns there as at its other corners. A dash of no length shows its caps alone, as a dot with RoundCap. No lengths, a negative one, or lengths that add up to none stroke the path whole. As Trim trims the path, its dashes stay where they are on it.
func (*Path) FillRule ¶
FillRule sets which points of the path a Painter fills, and clips to (FillPath, ClipPath), and Contains finds inside it, and returns the path: NonZero, the default, or EvenOdd, which makes a ring of two circles drawn the same way round:
var ring ui.Path ring.Circle(50, 50, 40).Circle(50, 50, 25).FillRule(ui.EvenOdd) p.FillPath(&ring, c.Theme().Accent)
func (*Path) Join ¶
Join sets how a Painter strokes the corners of the path, round by default, as SVG's stroke-linejoin, and returns the path.
func (*Path) MiterLimit ¶
MiterLimit sets how far the point of a MiterJoin may reach from its corner, in half the stroke's width, as SVG's stroke-miterlimit, and returns the path: a corner sharper than that is bevelled. It is 4 by default, which bevels corners sharper than about 29 degrees, and at least 1.
func (*Path) Reset ¶
Reset empties the path and removes Trim, its FillRule and the stroke's caps, joins and dashes, retaining its storage.
func (*Path) Trim ¶
Trim keeps of the path, as a Painter fills or strokes it, the part of its length from from to to, as fractions of it, its subpaths one after another, and returns the path: 0 to 0.5 draws its first half, and a check mark draws itself as to animates from 0 to 1, as SwiftUI's trim(from:to:) and Motion's pathLength. Trimmed, closed subpaths draw open, and a stroke trimmed shorter than its width fades with its length, rather than its round or square caps showing a dot that comes or goes at once.
type Placement ¶
type Placement struct {
// contains filtered or unexported fields
}
A Placement says where along the timeline a tween or a label starts: relative to the tween before it, at a label, or at a time, as GSAP's position parameter. With no placement, what comes next follows the tween before it at once, as AfterPrevious(0). Nothing starts before the timeline does: a placement before its start is at its start.
tl.Tween(ui.Tween{...}, ui.AfterPrevious(-150*time.Millisecond)) // overlaps it by 150ms
tl.Tween(ui.Tween{...}, ui.WithPrevious(100*time.Millisecond))
tl.Tween(ui.Tween{...}, ui.AtLabel("intro", 200*time.Millisecond))
tl.Tween(ui.Tween{...}, ui.AtTime(500*time.Millisecond))
func AfterPrevious ¶
AfterPrevious starts a tween offset after the tween before it ends, or with a negative offset that long before, to overlap it, as GSAP's "+=" and "-=".
func AtLabel ¶
AtLabel starts a tween offset after a Label of the timeline, as rows staggered from one label each start i times a step after it:
for i := range rows {
rows[i] = tl.Tween(ui.Tween{From: 0, To: 1, Duration: 200 * time.Millisecond},
ui.AtLabel("rows", time.Duration(i)*40*time.Millisecond))
}
func WithPrevious ¶
WithPrevious starts a tween offset after the tween before it starts, to move something along with it, as GSAP's "<".
type PlanarSurface ¶
type PlanarSurface struct {
// contains filtered or unexported fields
}
PlanarSurface maps a rectangular panel with no transform. It is the simple case used by ordinary native panels and cards.
func NewPlanarSurface ¶
func NewPlanarSurface(rect Rect) *PlanarSurface
NewPlanarSurface returns a map for rect in the presenting element's DIPs.
func (*PlanarSurface) ScreenToSurface ¶
func (s *PlanarSurface) ScreenToSurface(p Point) (SurfaceHit, bool)
func (*PlanarSurface) SetRect ¶
func (s *PlanarSurface) SetRect(rect Rect)
SetRect changes the panel's screen rectangle.
func (*PlanarSurface) SetVersion ¶
func (s *PlanarSurface) SetVersion(v uint64)
SetVersion records the geometry version this map describes.
func (*PlanarSurface) SurfaceToScreen ¶
func (s *PlanarSurface) SurfaceToScreen(uv UV) (Point, bool)
func (*PlanarSurface) Version ¶
func (s *PlanarSurface) Version() uint64
type Point ¶
type Point struct{ X, Y float32 }
Point is a position in DIPs relative to an element or text layout.
type PointerAccuracy ¶
type PointerAccuracy uint8
PointerAccuracy is how accurately a pointing device points.
const ( // PointerFine is a mouse's, a touchpad's or a pen's: the default. PointerFine PointerAccuracy = iota // PointerCoarse is a finger's on a touch screen, which wants larger // targets. PointerCoarse // PointerNone is that of no pointing device, as a keyboard alone. PointerNone )
type PointerType ¶
type PointerType uint8
PointerType is the kind of device moving the pointer, as Pointer Events' pointerType.
type PopoverMenuButtonOptions ¶ added in v0.1.1
type PopoverMenuButtonOptions struct {
// At and Self place the menu as AttachTo places an element, its point
// Self on the point At of the button's box: AnchorBottomEnd and
// AnchorTopEnd line it up with the button's end, below it;
// AnchorTopStart and AnchorBottomStart, or AnchorTopEnd and
// AnchorBottomEnd, put it above the button; AnchorTopEnd and
// AnchorTopStart put it after the button, beside it. Where the window
// has no room, it goes to the other side of the button, or the other
// way along it, as AttachTo's elements do, keeping its gap from the
// button. Both zero (AnchorTopLeft) are the default, AnchorBottomStart
// and AnchorTopStart. A menu opened at a point, as a toolbar's
// overflow menu opens its buttons' menus, shows there instead.
At, Self Anchor
// Open, when set, is whether the menu shows, as MenuBase's open: the
// button sets it as the menu opens and closes, and the app opens the
// menu by setting it to true and closes it by setting it to false
// before the button is built, as an event of the app's in the
// background does before it updates the window. A menu opened so
// takes the focus, with no item highlighted, and gives it back as it
// closes. A window shows one such menu at a time: another opening
// closes it, which sets *Open to false, as a disabled button, which
// opens none, does.
Open *bool
}
PopoverMenuButtonOptions are how a menu button whose menu MyGo draws in the window (PopoverMenuButton) shows it. The zero options show it below the button, lined up with its start, opened and closed by the user alone.
type Popup ¶
type Popup uint8
Popup is the kind of popup an element opens (Element.HasPopup), as ARIA's aria-haspopup says.
const ( // PopupNone opens no popup. PopupNone Popup = iota // PopupMenu opens a menu, aria-haspopup="menu" (or "true"). PopupMenu // PopupListBox opens a list of options, as a select's. PopupListBox // PopupTree opens a tree, PopupGrid a grid, as a date picker's // calendar, and PopupDialog a dialog. PopupTree PopupGrid PopupDialog )
type Pose ¶
Pose is where an element shows, from its place in the layout, which AnimatePose moves it to: moved by X and Y DIPs, and by XPercent and YPercent percent of its own width and height, as TranslatePercent moves it, scaled by Scale around its TransformOrigin (0 keeps its size, as 1 does), turned by Rotate degrees clockwise, and faded by Fade, from 0, opaque, to 1, gone.
type Preferences ¶
type Preferences struct {
// Accent is the accent color the user chose, which the default theme
// takes; A is 0 where the desktop has none.
Accent Color
// ReduceMotion asks for less motion: macOS's Reduce Motion, Windows's
// animation effects and GNOME's animations turned off. Animate then
// goes to its target at once; Loop, which shows that something is
// going on, goes on.
ReduceMotion bool
// ReduceTransparency asks for opaque surfaces in place of translucent
// ones: macOS's Reduce Transparency, Windows's transparency effects
// turned off. Materials should fall back to an opaque surface, as the
// glass plugin does; windows' own materials follow it already.
ReduceTransparency bool
// HighContrast asks for more contrast: macOS's Increase Contrast,
// Windows's contrast themes, the desktop portal's higher contrast. The
// default theme then draws borders and secondary text darker (lighter
// in the dark), and the focus ring opaque.
HighContrast bool
// TextScale is how many times larger than usual text should be, as
// Windows's and GNOME's text size settings say, 1 for usual: the
// default theme's FontSize is that much larger.
TextScale float32
// Pointer is how accurately the primary pointing device points, and
// AnyPointer the most accurate of all, as Media Queries 4's pointer
// and any-pointer: PointerFine for a mouse, a touchpad or a pen,
// PointerCoarse for a touch screen alone, or in Windows's tablet mode.
// A touch-first layout, with larger targets, reads Pointer; macOS's
// and those not known are a mouse's.
Pointer, AnyPointer PointerAccuracy
// NoHover tells that the primary pointing device cannot hover, as a
// finger on a touch screen, and NoAnyHover that none can: Media
// Queries 4's hover: none and any-hover: none. Hover and AnyHover say
// the opposite. Tooltips and what shows on hover alone want a pointer
// that hovers.
NoHover, NoAnyHover bool
}
Preferences are settings of the desktop that the system's own controls follow. The default theme follows them, and Animate follows ReduceMotion; a theme of your own (Context.SetTheme) and drawing of your own may read them with Context.Preferences.
func (Preferences) AnyHover ¶
func (p Preferences) AnyHover() bool
AnyHover reports whether any pointing device can hover, as Media Queries 4's any-hover: hover.
func (Preferences) Hover ¶
func (p Preferences) Hover() bool
Hover reports whether the primary pointing device can hover, as Media Queries 4's hover: hover.
type ProjectiveSurface ¶
type ProjectiveSurface struct {
// contains filtered or unexported fields
}
ProjectiveSurface maps a rectangular surface through a Transform, including a RotateY/Perspective pair. The inverse is used for pointer input, so a surface that turns away from the viewer reports no hit.
func NewProjectiveSurface ¶
func NewProjectiveSurface(rect Rect, t Transform) *ProjectiveSurface
NewProjectiveSurface returns a map for rect transformed by t. The transform is around the center of rect, as Element.Transform is around an element's center by default.
func (*ProjectiveSurface) ScreenToSurface ¶
func (s *ProjectiveSurface) ScreenToSurface(p Point) (SurfaceHit, bool)
func (*ProjectiveSurface) SetRect ¶
func (s *ProjectiveSurface) SetRect(rect Rect)
SetRect changes the panel's screen rectangle and recomputes the map.
func (*ProjectiveSurface) SetTransform ¶
func (s *ProjectiveSurface) SetTransform(t Transform)
SetTransform changes the surface transform and recomputes the map.
func (*ProjectiveSurface) SetVersion ¶
func (s *ProjectiveSurface) SetVersion(v uint64)
SetVersion records the geometry version this map describes.
func (*ProjectiveSurface) SurfaceToScreen ¶
func (s *ProjectiveSurface) SurfaceToScreen(uv UV) (Point, bool)
func (*ProjectiveSurface) Version ¶
func (s *ProjectiveSurface) Version() uint64
type RadialGradient ¶
type RadialGradient struct {
Stops []GradientStop
// Center is the point the colors spread from, in fractions of the
// box's width and height from its top left corner; the zero Point is
// its middle, as ConicGradient's is.
Center Point
// Radius is how far the gradient reaches from its center, in DIPs; 0
// reaches the corner of the box farthest from the center, as CSS's
// farthest-corner default does. The gradient shows its first color
// before the center and its last past the radius.
Radius float32
// Oklab mixes the colors in the Oklab color space, as LinearGradient's
// does.
Oklab bool
}
RadialGradient blends colors outwards from a point, as CSS's radial-gradient() does (SwiftUI's RadialGradient, Flutter's RadialGradient): its stops at their places from its center, at 0, to a circle of its radius, at 1.
e.RadialGradient(ui.RadialGradient{Stops: []ui.GradientStop{{white, 0}, {ui.Transparent, 1}}})
type Ref ¶
type Ref = Handle
Ref is an alias for Handle. Bind and Handle are preferred for new code.
type Role ¶
type Role uint8
Role is what an element is to assistive technology. Widgets set their own; other elements get one from what they do: one that is clickable and takes the focus is a button, a text is a text, a scroll container a scroll area, and one with a Label, or that takes the focus, a group.
const ( // RoleAuto finds the role from what the element does. RoleAuto Role = iota // RoleNone leaves the element out, but not its children. RoleNone RoleGroup RoleText RoleButton // RoleLink is a link: focused, it takes Enter but not Space, which // scrolls, as in a web page. RoleLink RoleCheckBox RoleRadio RoleSwitch RoleSlider RoleProgress RoleTextField RoleImage RoleList RoleScroll RoleDialog RolePopup RoleTooltip RolePopUpButton RoleTabList RoleTab RoleSplitter RoleStatus RoleTable RoleRow RoleCell RoleColumnHeader RoleTree RoleTreeItem // RoleListItem is an item of a list: the rows of a List are. RoleListItem // RoleMenuButton is a button opening a menu (Element.Menu). RoleMenuButton // RoleToolbar holds controls (Toolbar), RoleRadioGroup radio buttons // (RadioGroup, Segmented), and RoleToggleButton is a button that stays // pressed (Toggle). RoleToolbar RoleRadioGroup RoleToggleButton // RoleComboBox is a text input with a popup of options (ComboboxBase). RoleComboBox // RoleDisclosure is a button showing or hiding content below it, as // the trigger of a collapsible (CollapsibleBase), expanded while open. RoleDisclosure // RoleMeter shows a value in a range (Meter), and RoleStepper steps a // value in one (Stepper). RoleMeter RoleStepper // RoleColorWell is a button showing a color, which it opens a picker // of (ColorWell). RoleColorWell // RoleAlertDialog is a dialog asking about something important // (AlertDialog). RoleAlertDialog // RoleMenu holds the items of a menu drawn in the window, as a drop-down // menu's panel, and RoleMenuBar the titles of menus along it. // RoleMenuItem is an item of either, and RoleMenuItemCheckBox and // RoleMenuItemRadio items showing a choice, checked with Checked. RoleMenu RoleMenuBar RoleMenuItem RoleMenuItemCheckBox RoleMenuItemRadio // RoleHeading is the title of a section, named by its text, its rank // set with Level. RoleHeading // RoleRegion is a landmark with a Label, as an activity feed or a // panel: screen readers list it among the window's landmarks, and // jump to it. Without a Label it is a group, as ARIA's region. RoleRegion // RoleLog is a live region of messages added in order, as a chat's // transcript: screen readers read out what is added to it, once it has // shown, after what they are reading. RoleLog // RoleTimer counts time, as a countdown, whose changes screen readers // read only when the user goes to it. RoleTimer // RoleAlert is a live region of important news, as a field's error: // screen readers read its content out at once, interrupting what they // are reading, as it appears and whenever it changes. RoleAlert // RoleSeparator divides groups of content or controls, as a rule // between a toolbar's groups of buttons (a Divider): screen readers // read it as running up and down when it is taller than wide. RoleSeparator // RoleRowHeader is the cell naming its row of a table, as // RoleColumnHeader names a column. RoleRowHeader // RoleSearch is a landmark holding what searches the app or a // document, as the search field and its button at the top of a // window: screen readers list it among the window's landmarks, and // jump to it. RoleSearch // RoleArticle is a self-contained piece of content, as a post of a // feed or a comment of a thread, named by its Label: screen readers // step from one article to the next, as HTML's article. RoleArticle // app or a document, as a breadcrumb trail (Breadcrumbs) or a // navigation bar: screen readers list it among the window's // landmarks, and jump to it. RoleNavigation // RoleGrid is a table whose cells take the focus and the arrow keys, // as a spreadsheet's, where RoleTable is one to read; RoleTreeGrid is // a grid whose rows open and close as a tree's items do (Expanded, // Level). Their rows, cells and headers are RoleRow, RoleCell, // RoleColumnHeader and RoleRowHeader, as a table's, and the rows of a // List shown as one are its rows. RoleGrid RoleTreeGrid // RoleListBox is a list of options to choose from, as ARIA's listbox, // and RoleOption one of its options, selected with Checked, as ARIA's // aria-selected: what a list of your own offers, such as suggestions // at a text area's caret whose highlighted one the text area points // at with ActiveDescendant. The popups of SelectBase and ComboboxBase // are list boxes. RoleListBox RoleOption // RoleDeletion and RoleInsertion hold content removed from or added // to a document, as HTML's del and ins, ARIA's deletion and // insertion: the removed and added lines of a diff, or an old price // struck out beside the new one. Screen readers read their text with // "deletion" or "insertion" rather than as plain text. They take no // Label: the text inside them is what they hold. // // ui.Row(c).Gap(6).Children(func() { // ui.Text(c, "$40").Strikethrough().Role(ui.RoleDeletion) // ui.Text(c, "$30").Role(ui.RoleInsertion) // }) RoleDeletion RoleInsertion )
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route is a page a Router's View builds: Match tells its path apart and Param reads the parts of the path the pattern matched.
func (*Route) Match ¶
Match reports whether the page's path matches pattern, whose parts between slashes are either the same as the path's or wildcards: {name} takes any one part, and {name...}, at the end, the rest of the path, which may be empty. Param returns what they took. A slash at the end of the path or the pattern makes no difference.
case r.Match("/notes/{id}"): // "/notes/42"
case r.Match("/files/{path...}"): // "/files", "/files/docs/a.txt"
func (*Route) Page ¶
Page returns the element holding the page, a column filling the router, for its style.
func (*Route) Param ¶
Param returns what the wildcard name of the pattern Match last matched took, unescaped, or of a layout's around, "" if none has it.
func (*Route) Path ¶
Path returns the path of the page, as "/notes/42"; in a Route.View, the part of the path its layout leaves, as "/fonts" of "/settings/fonts".
func (*Route) Title ¶
Title names the page: screen readers read it as the page shows, and BackButton and ForwardButton list it. Inside a layout, the title of the page inside names the entry of the history.
func (*Route) View ¶
View builds the pages of the rest of the path, which the {name...} wildcard of the pattern Match matched last took, with fn, in a column taking the room it is given, and returns the column: the page holding it is a layout, as a page of settings with a list of its sections around the section shown. The layout stays as the pages inside change, keeping its state, and they slide or fade in its place, keep their state in the history and take the focus as the router's pages do. Their patterns match the rest of the path, and Param returns the wildcards of the layout's pattern too:
case r.Match("/settings/{section...}"):
app.settingsSidebar(c)
r.View(c, func(r *ui.Route) {
switch {
case r.Match("/general"):
app.general(c)
case r.Match("/fonts"):
app.fonts(c)
}
})
View panics when the pattern Match matched last has no {name...}.
type Router ¶
type Router struct {
Handle
// Transition is how pages replace each other, and Animation, if set,
// how they move then: as a spring (Snappy, …) or a curve, rather than
// easing out over 250 ms as they slide, 150 ms as they fade, and 300
// ms as they fade into each other (TransitionMatch).
Transition Transition
Animation *Animation
// contains filtered or unexported fields
}
Router keeps the history of the pages of a window, or of a part of one, as a browser does for a tab: the page shown, those before it that Back returns to, and those after it that Forward goes to again. A page is a path, as "/notes/42?tab=info", and View builds the one shown. Make a router once, in a field of the app's state, and build its pages in the view:
type notesApp struct{ router *ui.Router }
app := ¬esApp{router: ui.NewRouter("/notes")}
func (app *notesApp) view(c *ui.Context) {
app.router.View(c, func(r *ui.Route) {
switch {
case r.Match("/notes"):
r.Title("Notes")
app.notes(c)
case r.Match("/notes/{id}"):
r.Title("Note")
app.note(c, r.Param("id"))
default:
ui.Text(c, "Not found")
}
})
}
Push goes to a page and Back comes back, as do Cmd+[ and Cmd+] on macOS, Alt+Left and Alt+Right elsewhere, the back and forward buttons of a mouse, BackButton and ForwardButton, and Links to paths in its pages.
A page can be a layout around the pages of the rest of the path, which Route.View builds: the layout stays, keeping its state, as they change inside it.
A page keeps the state of its elements while it is in the history: going back to one finds it scrolled where it was, with what was typed, and the keyboard focus where it was. Going to a page moves the focus into it, unless the focus is outside the page that changes, as in a sidebar choosing the pages, where it stays: screen readers then hear the title of the page. Pages slide or fade in (Transition).
In a browser, the first router a window shows follows the history of the browser's tab, in the URL's fragment, as "#/notes/42": going to a page adds an entry to it, the browser's back and forward buttons go through the router's pages, and a URL with a fragment opens the app at its page.
The zero Router shows "/". As the rest of the app's state, it is read and changed on the main thread: from another goroutine, change it in Window.Update.
func (*Router) CanGoBack ¶
CanGoBack reports whether there is a page to go back to, and CanGoForward one to go forward to.
func (*Router) CanGoForward ¶
func (*Router) Forward ¶
func (r *Router) Forward()
Forward shows the page after, which Back left, if any.
func (*Router) Go ¶
Go moves n pages through the history: back for a negative n, forward for a positive one, as far as it goes.
func (*Router) Location ¶
Location returns the path and the query of the page shown, as "/notes/42?tab=info", which Push and Replace take, to show the page again when the app starts.
func (*Router) Push ¶
Push goes to the page at target, after the page shown, whose later pages it forgets: an absolute path, as "/notes/42", or one relative to the page shown, as a link in a web page, as "?tab=info" or "../". Going to the page shown does nothing. The same path with another query is the same page, keeping its state, in another entry of the history, and layouts whose part of the path stays stay too.
func (*Router) Query ¶
Query returns the value of the query parameter name of the page shown, "" if it has none.
func (*Router) Replace ¶
Replace shows the page at target in place of the page shown, in its entry of the history, as after a page moved: Back does not return to the page replaced. The same path with another query is the same page, keeping its state, as a search page following what is typed.
type SVG ¶
type SVG struct {
// contains filtered or unexported fields
}
SVG is a vector image: an icon, a logo, an illustration. It stays sharp at any size. Parse it once, not in the view, and show it with Icon, in the color of the text, or with Image, in its own colors:
//go:embed icons/save.svg var saveSVG []byte var save = ui.MustParseSVG(saveSVG) ui.Icon(c, save)
MyGo draws the paths and basic shapes of SVG, with groups, use and symbol elements, transforms, colors, gradients, strokes and their dashes, opacity, clip paths, masks and style sheets of simple selectors. It leaves out text, embedded images, patterns, markers and filters: convert text to paths before.
func MustParseSVG ¶
MustParseSVG is ParseSVG for SVGs that are part of the program, such as embedded files: it panics when one is in error.
func (*SVG) Image ¶ added in v0.1.1
Image draws the SVG in its own colors to an image of w by h pixels, fitting it in them as its preserveAspectRatio says, with current for currentColor, black when nil: for what takes pixels rather than an element, as mygo.NewMenuIconSVG draws a menu's icon. Painter.Icon and Icon draw it in the window, at the display's scale.
type ScrollAlign ¶
type ScrollAlign uint8
ScrollAlign is where ScrollIntoView lines an element up in a container on an axis, as the web's ScrollLogicalPosition.
const ( // ScrollNearest scrolls as little as shows the element: not at all // when it shows, and to the nearer edge otherwise. What is larger than // the view shows from its start. ScrollNearest ScrollAlign = iota // ScrollStart lines the element's start up with the container's: its // top, or its left (its right, right to left). ScrollStart // ScrollCenter puts the element in the middle of the container. ScrollCenter // ScrollEnd lines the element's end up with the container's. ScrollEnd )
type ScrollIntoViewOptions ¶
type ScrollIntoViewOptions struct {
// Block and Inline line the element up in each container around it,
// vertically and sideways, as the web's block and inline do:
// ScrollNearest scrolls as little as shows it, and ScrollStart,
// ScrollCenter and ScrollEnd line its start, center or end up with
// the container's, inside its border. Right to left, the inline start
// is at the right.
Block, Inline ScrollAlign
// Animation, when set, glides the containers there as it says (Smooth,
// a spring, or a curve), as the web's behavior: "smooth" does, rather
// than at once. The user scrolling, or the app, stops it. While the
// desktop asks for less motion, or the frame disables animations, it
// scrolls at once.
Animation *Animation
}
ScrollIntoViewOptions say where ScrollIntoView brings an element in the containers around it, and how, as the web's ScrollIntoViewOptions do. The zero options scroll as little as shows it, at once, as ScrollIntoView does without them.
type ScrollState ¶
type ScrollState struct {
Handle
// X and Y are how far the content is scrolled left and up, in DIPs:
// right to left (Direction), X is how far it is scrolled right, from
// its start at the right. Set them to scroll: the container keeps them
// within its content, so that 0 shows the start and math.MaxFloat32
// the end.
X, Y float32
// MaxX and MaxY are as far as X and Y go, as the frame laid the content
// out: Y is MaxY at the end. The container sets them.
MaxX, MaxY float32
// contains filtered or unexported fields
}
ScrollState is how far a scroll container scrolls its content, kept in the app's state with TrackScroll.
func (*ScrollState) ScrollTo ¶
func (s *ScrollState) ScrollTo(x, y float32, a Animation)
ScrollTo scrolls the container smoothly to x and y as a says, from where it shows its content, as SwiftUI's scrollTo in withAnimation: math.MaxFloat32 is the end. Called again on the way, it turns smoothly toward the new place; the user scrolling stops it. While the desktop asks for less motion, or the frame disables animations, it scrolls at once.
if ui.Button(c, "Back to top").Clicked() {
app.feed.ScrollTo(0, 0, ui.Smooth)
}
func (*ScrollState) Scrolling ¶
func (s *ScrollState) Scrolling() bool
Scrolling reports whether a ScrollTo is on its way.
type Scrollbar ¶
type Scrollbar struct {
// Box is the view the bar runs along, at its right edge, or its
// bottom edge for a horizontal bar, in the coordinates the bar is
// painted or hit tested in.
Box Rect
// Horizontal makes the bar run along the bottom, scrolling sideways.
Horizontal bool
// View is the length of the content the view shows, Content the
// length of all of it, and Offset how far it is scrolled, in any
// unit, as rows of a terminal's scrollback: the bar shows nothing
// unless Content is longer than View.
View, Content, Offset float32
}
Scrollbar is the scroll bar of a view that scrolls itself rather than through a scroll container, as a code editor or a terminal does, laid out and painted as a scroll container's are, so that every bar of an app looks alike and follows the theme (Theme.Scrollbar, ScrollbarWidth).
The view paints the bar with Painter.Scrollbar while it shows it: a scroll container's show while the pointer is over the container or drags a thumb, and maps a drag of the thumb to an offset with Thumb and OffsetAt.
bar := ui.Scrollbar{Box: r, View: viewH, Content: contentH, Offset: scrollY}
if hovered || dragging {
p.Scrollbar(bar, ui.ScrollbarState{Dragging: dragging})
}
func (Scrollbar) OffsetAt ¶
OffsetAt returns the offset that brings the thumb's start to start, as the thumb is dragged, within the content.
type ScrollbarState ¶
ScrollbarState is how a Scrollbar paints: Dragging while the pointer drags its thumb, which widens it, as a scroll container's; Color, if not zero, colors it for a view whose colors are not the theme's, as a terminal's, in place of Theme.Scrollbar.
type SegmentedParts ¶
type SegmentedParts struct {
Track Element
// contains filtered or unexported fields
}
SegmentedParts contains checked handles for the parts of a custom widget.
func SegmentedBase ¶
func SegmentedBase(c *Context, selected *int, n int) SegmentedParts
SegmentedBase creates a segmented control of n segments without a look, of which *selected is the index of the one chosen: a radio group (see RadioGroup) whose radio buttons are the segments, built in Track with Segment. Track's Changed reports a new choice. Segmented is SegmentedBase with the theme's look.
func (SegmentedParts) Segment ¶
func (_handle SegmentedParts) Segment(i int) Element
Segment creates segment i: a radio button choosing i. Style it from whether i is the one chosen, and give it children.
type SelectParts ¶
type SelectParts[T comparable] struct { Trigger Element // contains filtered or unexported fields }
SelectParts contains checked handles for the parts of a custom widget.
func SelectBase ¶
func SelectBase[T comparable](c *Context, selected *T) SelectParts[T]
SelectBase creates a select without a look: a trigger that opens a popup of options, which choose *selected. With the focus on the trigger, the arrows open the popup and move among its options, past those disabled, as do Home and End; Enter and Space choose one, and Escape closes it; the trigger's Changed reports a new choice. Give the trigger children showing the choice, and build the options in Popup with Item:
sel := ui.SelectBase(c, &app.size)
sel.Trigger.Padding(6, 10).Border(1, gray).Children(func() {
ui.Text(c, app.size)
})
sel.Popup(func(panel ui.Element) {
panel.Padding(4).Background(white).Border(1, gray)
for _, size := range sizes {
item := sel.Item(size).Padding(6, 10)
if item.Highlighted() {
item.Background(blue).TextColor(white)
}
item.Children(func() { ui.Text(c, size) })
}
})
Select is SelectBase with the theme's look.
func SelectBaseOpen ¶
func SelectBaseOpen[T comparable](c *Context, selected *T, open *bool) SelectParts[T]
SelectBaseOpen is SelectBase whose popup shows while *open, a flag the caller owns, as PopoverBase's: the select sets it as it opens and closes, and the caller may set it too, as typing on the closed trigger opens the popup, or Tab moving on closes it. The highlight starts on the choice each time the popup opens. Owning the flag, the caller can keep the popup a little longer as it closes, to shrink it back into the trigger.
func (SelectParts[T]) Highlight ¶
func (_handle SelectParts[T]) Highlight(value T)
Highlight moves the highlight to the option of value while the popup shows, unless it is disabled, as a select of your own may do as the user types the option's first letters; Enter then chooses it. Called before Popup as the popup opens, it highlights the option once Popup builds it.
func (SelectParts[T]) Item ¶
func (_handle SelectParts[T]) Item(value T) Element
Item creates an option choosing value: a row that is Highlighted when the pointer or the arrows are on it, and chooses value and closes the popup when clicked. Disabled leaves it out of the keys' way and of the pointer's. The option the highlight moves to scrolls into view, once, so that the wheel scrolls on past it. Assistive technology reads it as an option of a list box (RoleOption), selected while it is highlighted, as a native select's; focusing it highlights it, and pressing it chooses it.
func (SelectParts[T]) Open ¶
func (_handle SelectParts[T]) Open() bool
Open reports whether the popup shows.
func (SelectParts[T]) Popup ¶
func (_handle SelectParts[T]) Popup(fn func(panel Element)) Element
Popup shows the popup below the trigger, at least as wide, while it is open: fn styles the panel and builds the options in it with Item. Clicking outside it or pressing Escape closes it. It returns the panel, or nil when the popup is closed.
func (SelectParts[T]) SetOpen ¶
func (_handle SelectParts[T]) SetOpen(o bool)
SetOpen opens or closes the popup, as typing on the closed trigger may open it, or Tab moving on close it. It opens with the highlight on the choice, which Highlight then moves.
type SelectedText ¶
type SelectedText struct {
// ID is the paragraph's element's (Element.ID).
ID uint64
// Text is the paragraph's text, and Start and End the runes of it the
// selection holds.
Text string
Start, End int
}
SelectedText is the part of a paragraph that the selection of a Selectable container holds.
type Selection ¶
type Selection[K comparable] struct { // contains filtered or unexported fields }
A Selection is the rows chosen in a List or a Table that lets the user choose several (ListState.Selection), held by the keys of their items (ListState.Key), of type K: the choice stays with its items as rows come, go and move. Without a Key, rows are their indices, of type int. Its zero value is empty. The keys of items gone from the list stay until removed.
type app struct {
files []File
chosen ui.Selection[string] // their paths
list ui.ListState
}
app.list.Key = func(i int) any { return app.files[i].Path }
app.list.Selection = &app.chosen
type Selector ¶
type Selector interface {
// contains filtered or unexported methods
}
A Selector is what ListState.Selection takes: a *Selection.
type Services ¶
type Services struct {
// contains filtered or unexported fields
}
Services provides persistent window services for custom controls and asynchronous work. It owns no frame data and does not retain the window. Clipboard and URL methods run on the UI thread; Invalidate may run on any goroutine. Models are still updated through Window.Update.
func (Services) ClipboardFormats ¶
ClipboardFormats lists the formats on the clipboard without reading them, as a paste decides what to read: an image comes as transfer.PNG whatever the system's format, which ReadClipboardData converts.
func (Services) Invalidate ¶
func (s Services) Invalidate()
func (Services) ReadClipboard ¶
func (Services) ReadClipboardData ¶
ReadClipboardData reads the clipboard's representations of formats, as a rich text editor reads its own format, HTML and plain text to paste the richest it understands; nil formats read all. A clipboard without them gives an empty Data.
func (Services) WriteClipboard ¶
func (Services) WriteClipboardData ¶
WriteClipboardData puts data on the clipboard, each representation of its items in the system's formats, as a rich text editor copies its own format, HTML and plain text.
type ShaderInput ¶
type ShaderInput struct {
Uniforms, WideUniforms []uint32
Images [4]*Bitmap
// Blur, for a shader reading its backdrop, is the standard deviation
// of the backdrop's blur, in pixels.
Blur float32
}
ShaderInput is what the effect of a shader of package ui/shader reads: the words of its uniforms' lanes, the words a wide gamut reads in their place (nil when the same), from EffectWords, and up to four images, bitmaps or canvases' (nil for none).
type Snap ¶
type Snap uint8
Snap is how a scroll container comes to rest at the places the elements in it mark (ScrollSnap), as CSS's scroll-snap-type.
const ( // SnapNone, the zero value, rests wherever the scrolling stops. SnapNone Snap = iota // SnapMandatory always rests at a place, as CSS's mandatory: a strip // of cards rests showing a card from its start, and a notch of a // wheel or an arrow key goes on to the next card. SnapMandatory // SnapProximity rests at a place only where the scrolling stops // near it, within a third of the view, as CSS's proximity, and // wherever it stops in between. SnapProximity )
type SortDirection ¶
type SortDirection uint8
SortDirection is the order a table's rows are sorted in by a column (Element.Sort), as ARIA's aria-sort says.
const ( // SortNone is not sorted by the column. SortNone SortDirection = iota // SortAscending and SortDescending sort the rows up or down the // column's values. SortAscending SortDescending // SortOther sorts them in an order of another kind. SortOther )
type SortOrder ¶
SortOrder is how a table's rows are sorted: by the column whose ID is Column, in ascending order unless Descending.
type Span ¶
type Span struct {
Text string
Font string // a family, as for Element.Font
Size float32
Weight int
Italic bool
Color Color
Underline bool
WavyUnderline bool
DottedUnderline bool
Strikethrough bool
// DecorationColor and DecorationThickness are those of the span's
// underline and strikethrough, as for Element.DecorationColor.
DecorationColor Color
DecorationThickness float32
// UnderlineOffset puts the span's underline that many DIPs below the
// baseline, or above it when negative, as for Element.UnderlineOffset;
// zero leaves it where the text around it has it.
UnderlineOffset float32
// Background highlights the span, as search results are.
Background Color
// Radius rounds the corners of the Background, which then hugs the
// span's glyphs, a little wider than them, rather than filling the
// line, as code within text shows.
Radius float32
// PaddingX and PaddingY pad the Background, which then hugs the
// span's glyphs, as CSS pads an inline box: a key cap, a mention chip.
// PaddingX, which replaces the little that Radius widens it by, also
// takes room in the line, moving the span's glyphs in and the text
// after them on; PaddingY only paints, over the lines above and below,
// as the background of an inline box does on the web. Each
// line's piece of a span that wraps gets both, and its corners, as
// with CSS's box-decoration-break: clone.
PaddingX, PaddingY float32
LetterSpacing float32
// NoLetterSpacing makes a zero LetterSpacing the span's own, rather
// than the text's around it, as CSS's letter-spacing: 0 on an inline
// box: digits or code within tracked capitals.
NoLetterSpacing bool
Features string // as for Element.FontFeatures, comma separated
Lang string // the language, as for Element.Lang
// ObjectWidth and ObjectHeight, when ObjectWidth is set, make each
// rune of the span, an object replacement character (U+FFFC), an
// inline object: a box of that size in DIPs standing on the baseline,
// which lines break around and which draws nothing, where a rich text
// editor draws an image (TextLayout.Objects) and a text what
// Element.DrawObjects draws. ObjectDescent extends the box that far
// below the baseline, as math's subscripts and fractions go: the line
// makes room for it.
ObjectWidth, ObjectHeight, ObjectDescent float32
// BaselineShift raises the span's text, or its objects, that many
// DIPs above the baseline, or lowers it when negative, as superscripts
// and subscripts with a smaller Size: footnote references, exponents,
// chemical formulas. The line makes room for it, and its underline
// and strikethrough go with it.
BaselineShift float32
// Shadow is the shadow the span's text casts (NewTextShadow), as
// Element.TextShadow casts one: zero casts that of the text around it.
Shadow TextShadow
// contains filtered or unexported fields
}
Span is a run of a RichText with a style of its own. What it leaves zero takes the style of the text around it, and Italic, Underline, WavyUnderline, DottedUnderline and Strikethrough only turn those on.
type SpringOptions ¶
type SpringOptions struct {
Duration time.Duration
Bounce float64
Mass, Stiffness, Damping float64
Precision float64
Velocity float32
}
SpringOptions describe a spring, as one perceives it or physically.
Duration and Bounce describe it as SwiftUI and Motion do: Duration is about how long it takes to arrive (500 ms when zero), and Bounce how much it overshoots, from 0, settling without overshooting, toward 1, bouncing for ever; below 0 it arrives more slowly still.
Mass, Stiffness and Damping describe it physically instead, as react spring does (1, 170 and 26 when zero), when Stiffness or Damping is set; setting them with Duration or Bounce panics.
Precision is how close to its target, in the value's units, the spring rests there: 0.001 when zero. Velocity, in value units per second, is the velocity the value takes when its target changes in the call, as that of a pointer letting go of what it dragged (DragEnded); zero keeps the value's own.
type SurfaceHit ¶
SurfaceHit is a pointer hit on a presented surface.
type SurfaceMap ¶
type SurfaceMap interface {
Version() uint64
ScreenToSurface(Point) (SurfaceHit, bool)
SurfaceToScreen(UV) (Point, bool)
}
SurfaceMap maps between the presenting element's local points and the parameter space of a surface. InputEvent coordinates are element-local, and text-input geometry uses the same space. Implementations for cloth, heightfields, meshes, or other deformable surfaces belong to the package that owns that surface.
Version identifies the geometry snapshot the mapping was made from. Callers comparing a pointer hit with a rendered layer should use the same version that rendered that layer; a stale mapping can put a click beside the pixels the user saw. A map may be rebuilt each frame, or may keep a stable version while its surface is unchanged.
type TableColumn ¶
type TableColumn struct {
// Title heads the column. ID identifies it among the others, for the
// order and the widths the user gives the columns (ListState.Columns)
// and for the sort (ListState.Sort and SortBy): the Title when empty.
Title, ID string
// Width is the column's width in DIPs, or 0 to share the room the
// others leave. The user resizes the column by dragging the right edge
// of its header, between MinWidth and MaxWidth (none for 0), and fits
// it to its cells with a double click there.
Width, MinWidth, MaxWidth float32
// Align aligns the content of its cells.
Align Align
// Sortable lets a click on the column's header sort the rows by it,
// with ListState.Sort or SortBy.
Sortable bool
// Fixed keeps the column where it is and as wide as it is: the user
// neither moves nor resizes it.
Fixed bool
// RowHeader marks a column of row headers, as a spreadsheet's row
// numbers: in a table choosing cells (ListState.CellSelect), a click or
// a drag on its cells chooses whole rows, with every column, and a
// click on its header chooses every row. It does not sort, and is
// never Cells.Cursor.
RowHeader bool
}
TableColumn describes a column of a Table.
type TableLayout ¶
TableLayout is the order and the widths the user gave the columns of a Table, by their IDs. Columns it does not name keep the order and the widths the table gives them.
type TabsParts ¶
type TabsParts struct {
List Element
// contains filtered or unexported fields
}
TabsParts contains checked handles for the parts of a custom widget.
func TabsBase ¶
TabsBase creates a list of n tabs without a look, of which *selected is the index of the one chosen. A click chooses a tab, as do the arrows, Home and End while one has the keyboard focus, which follows the choice, past the tabs disabled; List's Changed reports a new choice. Build the tabs in List with Tab:
tabs := ui.TabsBase(c, &app.tab, len(names))
tabs.List.Gap(4).Children(func() {
for i, name := range names {
tab := tabs.Tab(i).Padding(6, 12).Radius(6)
if i == app.tab {
tab.Background(c.Theme().Surface)
}
tab.Children(func() { ui.Text(c, name) })
}
})
Tabs is TabsBase with the theme's look.
type Tester ¶
type Tester struct {
// contains filtered or unexported fields
}
Tester runs a view without a window, as a test drives it: it renders frames in memory and sends the view pointer and keyboard input, between which it settles the frames the view asks for.
Its clock stands still unless the test moves it with Advance, so what depends on time (animations, Context.After, the clicks that make a double click, typing that undoes in one step, tooltips) does the same however fast the machine runs the test.
func NewTester ¶
NewTester starts testing view in a window of width×height DIPs. Two elements given one key under one parent make it panic where the second was given, as apps only log it.
func NewTesterWith ¶
func NewTesterWith(view func(c *Context), width int, height int, o TesterOptions) *Tester
NewTesterWith starts testing view in a window of width×height DIPs, as NewTester does, with the desktop's settings of o from the first frame:
tt := ui.NewTesterWith(view, 400, 300, ui.TesterOptions{Preferences: ui.Preferences{ReduceMotion: true}})
func (*Tester) Access ¶
func (t *Tester) Access(name string) (AccessInfo, bool)
Access returns what assistive technology sees of the first element of the last frame, in the order screen readers read them, whose accessible name is name: its Label, or the text it shows. The tree is the one screen readers would get, whether or not one reads the window, and reading it changes nothing.
func (*Tester) AccessAll ¶ added in v0.1.1
func (t *Tester) AccessAll() []AccessInfo
AccessAll returns what assistive technology sees of every element of the last frame, in the order screen readers read them, as Access gives each: to check what a whole view tells screen readers, as that every control has a name.
for _, a := range tt.AccessAll() {
if a.Role == ui.RoleButton && a.Name == "" {
t.Errorf("a button at %v has no name", a.Bounds)
}
}
func (*Tester) AccessByRole ¶
func (t *Tester) AccessByRole(r Role, name string) (AccessInfo, bool)
AccessByRole returns what assistive technology sees of the first element of the last frame with role r and the accessible name name, as Testing Library's getByRole(role, {name}) finds it; "" for name finds the first element of the role whatever its name.
func (*Tester) Advance ¶
Advance moves the Tester's clock on by d, running the frames due meanwhile at their times: one each refresh while something moves, and those of After and Painter.After when they come due. An animation of 200 ms is a quarter of the way after Advance(50 * time.Millisecond), and done after another Advance(150 * time.Millisecond).
func (*Tester) Announcements ¶
Announcements returns what the view asked screen readers to read out (Context.Announce), as a Router the titles of the pages it showed, and forgets it.
func (*Tester) CancelPress ¶
func (t *Tester) CancelPress()
CancelPress has the system take the pointer's press, as a browser's pointercancel does: every button held goes up without a release, which clicks nothing (InputEvent.Canceled, PressCanceled).
func (*Tester) ChooseMenuItem ¶
ChooseMenuItem chooses the item of the context menu shown labeled with the last of path, in the submenus the others label, and closes the menu.
func (*Tester) Click ¶
Click clicks the center of the element showing text or labeled s. It returns an error without sending input when no element shows s, it has no visible area, or its center would reach another control or nothing.
func (*Tester) ClickAtWith ¶
ClickAtWith clicks at (x, y), in DIPs, holding the modifier keys mods: a web view that takes the pointer there (WebViewAt) takes the click.
func (*Tester) ClickWith ¶
ClickWith clicks the center of the element showing text or labeled s holding the modifier keys mods, as a Shift-click. It checks the target before sending input, as Click does.
func (*Tester) Clipboard ¶
Clipboard returns the text the view copied; SetClipboard sets the text it pastes.
func (*Tester) ClipboardData ¶
ClipboardData returns what the view copied with Services.WriteClipboardData, or the text it copied; SetClipboardData puts data on the clipboard, as another app copies HTML.
func (*Tester) CloseMenu ¶
func (t *Tester) CloseMenu()
CloseMenu closes the context menu shown without choosing an item.
func (*Tester) CodeDown ¶
CodeDown presses a key that only its position names, as a modifier on its own or Caps Lock (InputEvent.Code): mods are the modifiers held with it, its own among them.
func (*Tester) CodeUp ¶
CodeUp lets go of a key CodeDown pressed: mods are the modifiers still held.
func (*Tester) Command ¶
Command performs an edit command of the menus, as Copy of the Edit menu: "copy", "cut", "paste", "pasteAndMatchStyle", "selectAll", "undo", "redo" or "delete", or a Format menu's, as "bold" or "alignCenter".
func (*Tester) Compose ¶
Compose shows text as an input method's composition, with its caret at rune caret, as while typing in Chinese or Japanese; an empty text ends it. Type commits the text. Nothing is composed while the focused element turned input methods off (InputMethod), as on the desktop.
func (*Tester) DropFiles ¶
DropFiles drops files dragged from another app at (x, y), as from Finder, and reports whether an element took them (DroppedFiles).
func (*Tester) FailClipboard ¶
FailClipboard makes the view's writes of text to the clipboard from now on fail with err, copying nothing, as a browser refuses them without the user acting (Context.WriteClipboardThen); nil lets them through again.
func (*Tester) FailOpenURL ¶
FailOpenURL makes the links the view opens from now on fail with err, as those no app opens, or opens them again for nil.
func (*Tester) Find ¶
Find returns the box of the first element showing text s, or labeled s, in the window's DIPs: zoomed (SetZoom), z times the content's.
func (*Tester) Focused ¶
Focused reports whether the element showing text or labeled s, or its container, has the keyboard focus.
func (*Tester) Frame ¶
func (t *Tester) Frame()
Frame renders another frame, as when the view's state changed.
func (*Tester) FramePending ¶
FramePending reports whether the view still asks for a frame, as one that animates or never settles does after an input or Frame. The frames of After and Painter.After wait for Advance to reach their time, as the clock stands still until then.
func (*Tester) HoldModifiers ¶
HoldModifiers presses or lets go of modifier keys on their own, as holding Cmd does, leaving mods held.
func (*Tester) KeyAt ¶
KeyAt presses a key that the active layout does not type as a US key (Key is KeyUnknown), at position physical of an ANSI US keyboard, as S is pressed on a Cyrillic layout.
func (*Tester) KeyDown ¶
KeyDown presses a key and holds it, as a player holds a key that walks, until KeyUp.
func (*Tester) KeyRepeat ¶
KeyRepeat presses a key with modifiers as its auto-repeat does while it is held down (InputEvent.Repeat, Context.ShortcutRepeated).
func (*Tester) Menu ¶
Menu returns the labels of the items of the context menu shown, "-" for separators, or nil when none is: the system's, or one drawn in the window (PopoverMenu, SetMenuPresentation).
func (*Tester) Now ¶
Now returns the Tester's time, that of its next frame, which stands still until Advance moves it.
func (*Tester) OpenedURLs ¶
OpenedURLs returns the links the view opened.
func (*Tester) Pinch ¶
Pinch zooms by scale with the pointer at (x, y), as pinching a touchpad does (InputZoom).
func (*Tester) PressButton ¶
PressButton presses (x, y) with the pointer's button, 0 the primary, 1 the secondary and 2 the middle, without releasing, as a right-button drag begins; ReleaseButton releases it.
func (*Tester) ReleaseButton ¶
ReleaseButton releases the pointer's button at (x, y).
func (*Tester) RightClick ¶
RightClick clicks the center of the element showing text or labeled s with the secondary button. It checks the target before sending input, as Click does. On an element without a context menu of its own, as a list's row, it opens the menu of the content the element holds there.
func (*Tester) RightClickAt ¶
RightClickAt clicks at (x, y), in DIPs, with the secondary button.
func (*Tester) Scroll ¶
Scroll scrolls by dx, dy DIPs with the pointer at (x, y), as a touchpad does: at once.
func (*Tester) SetClipboard ¶
SetClipboard sets the clipboard's text.
func (*Tester) SetClipboardData ¶
func (*Tester) SetDirection ¶
SetDirection lays the window out in d, as an app whose language reads so: RightToLeft lays it out from the right.
func (*Tester) SetFocused ¶
SetFocused gives the window the keyboard, or takes it away, as when the user switches to another window.
func (*Tester) SetLocale ¶
SetLocale makes tag the language the app shows, as mygo.App.SetLocale does: the view reads it with Context.Locale, and text without a language of its own is in it. A Tester starts with none, "", which draws text as the system does by default.
func (*Tester) SetPreferences ¶
func (t *Tester) SetPreferences(p Preferences)
SetPreferences changes the desktop's settings that controls follow, as the user does in the system's settings.
func (*Tester) SetRegion ¶
SetRegion changes the user's regional formats, which the view reads with Context.Region, as the user does in the system's settings. A Tester starts with the zero Region.
func (*Tester) SetTitleBar ¶
SetTitleBar sets the room the window controls of a window with a hidden title bar take, which Context.TitleBar returns.
func (*Tester) SetVibrancy ¶
SetVibrancy sets whether the window shows a material where the view draws no background, which Context.Vibrancy returns.
func (*Tester) SetWindowActive ¶
SetWindowActive draws the window as active, the window the user's input goes to, or not, as when the user switches to another window or app: Context.WindowActive returns it. It leaves the keyboard focus to SetFocused, as a window's flyout taking the keyboard leaves the window active.
func (*Tester) SetWindowHidden ¶
SetWindowHidden hides all of the window from sight, as minimizing it or covering it with other windows does, or shows it again: Context.WindowHidden returns it, and what moves waits while it is hidden.
func (*Tester) SetZoom ¶
SetZoom zooms the content by z, as the view's Context.SetZoom does. The Tester's coordinates stay the window's: Find, ClickAt, Move, Scroll and TextCaret are in its DIPs, the view's z times smaller.
func (*Tester) TextCaret ¶
TextCaret returns where input methods compose, and whether one would: the caret of the focused text input, or of an element's TextCaret, and not while it turned them off (InputMethod).
func (*Tester) TextInputActive ¶
TextInputActive reports whether the focused element takes text, typed or composed (HandleTextInput, TextCaret), and whether it turned input methods off (InputMethod), as the window tells the system.
func (*Tester) TypeKey ¶
TypeKey presses a key that types text, as a keyboard does: the key goes down, the text comes, then the key goes up.
func (*Tester) UsePointer ¶
func (t *Tester) UsePointer(pointer PointerType, pressure float32)
UsePointer has the pointer's presses and moves from now on come from the device pointer pressing with pressure, from 0 to 1, as a pen's, which a system tells: 0 is a mouse's, which tells none. The Tester starts with UsePointer(PointerMouse, 0). Calling it between moves while the pointer presses changes the pressure as a pen pressing harder does:
tt.UsePointer(ui.PointerPen, 0.2) tt.Press(10, 10) tt.UsePointer(ui.PointerPen, 0.9) tt.Move(10, 10) // the pen presses harder where it stands
func (*Tester) WebViewAt ¶
func (t *Tester) WebViewAt(x, y float32) NativeWebView
WebViewAt returns the web view (WebView) that takes the pointer at (x, y), as the window shows it: where the last frame showed it and painted nothing over it that takes the pointer; nil for none.
type TesterOptions ¶
type TesterOptions struct {
// Preferences are the desktop's settings that controls follow
// (SetPreferences).
Preferences Preferences
// Dark starts in the dark appearance (SetDark).
Dark bool
}
TesterOptions are settings of the desktop that a Tester starts with, which its first frame follows, as Media Queries 5 has the user's preferences apply from the first time styles resolve: a view mounted under ReduceMotion starts no animation in its first frames either, as it would before a SetPreferences after NewTester.
type TextAffinity ¶
TextAffinity chooses a caret's preceding or following logical edge. Bidi boundaries and soft wraps can give the same index two visual positions.
type TextBuffer ¶
type TextBuffer struct {
// contains filtered or unexported fields
}
TextBuffer stores editable UTF-8 text in an indexed, persistent tree. Small edits copy bounded chunks and tree paths, not the whole document. Rune offsets are used by Slice/Replace, matching Element.TextSelection; UTF16Offset/RuneOffset and TextForRange bridge native input coordinates. The zero value is an empty buffer. Methods are safe from any goroutine. Schedule edits with Window.Update to invalidate a view showing the buffer.
func NewTextBuffer ¶
func NewTextBuffer(s string) *TextBuffer
NewTextBuffer creates indexed storage owning its text chunks. A small surviving fragment cannot pin the original large input string.
func (*TextBuffer) ByteLen ¶
func (b *TextBuffer) ByteLen() int
func (*TextBuffer) Len ¶
func (b *TextBuffer) Len() int
func (*TextBuffer) LineCount ¶
func (b *TextBuffer) LineCount() int
func (*TextBuffer) Replace ¶
func (b *TextBuffer) Replace(start, end int, s string)
Replace replaces a half-open rune range, clamping it to the document.
func (*TextBuffer) ReplaceUTF16 ¶
func (b *TextBuffer) ReplaceUTF16(r TextInputRange, s string) TextInputRange
ReplaceUTF16 adjusts surrogate interiors down to whole runes, replaces the range, and returns the actual old UTF-16 range it replaced.
func (*TextBuffer) Restore ¶
func (b *TextBuffer) Restore(s TextSnapshot)
Restore adopts a snapshot in constant time and advances the version.
func (*TextBuffer) RuneOffset ¶
func (b *TextBuffer) RuneOffset(index int) int
func (*TextBuffer) Set ¶
func (b *TextBuffer) Set(s string)
Set replaces the document. Existing snapshots retain their own version.
func (*TextBuffer) Slice ¶
func (b *TextBuffer) Slice(start, end int) string
func (*TextBuffer) Snapshot ¶
func (b *TextBuffer) Snapshot() TextSnapshot
func (*TextBuffer) String ¶
func (b *TextBuffer) String() string
String materializes the document for export. Controls do not call it during ordinary editing; Slice and WriteTo avoid that full allocation.
func (*TextBuffer) TextForRange ¶
func (b *TextBuffer) TextForRange(r TextInputRange) (string, TextInputRange)
func (*TextBuffer) UTF16Len ¶
func (b *TextBuffer) UTF16Len() int
func (*TextBuffer) UTF16Offset ¶
func (b *TextBuffer) UTF16Offset(index int) int
func (*TextBuffer) Version ¶
func (b *TextBuffer) Version() uint64
type TextCaretPosition ¶
type TextCaretPosition struct {
Index int
Affinity TextAffinity
}
TextCaretPosition retains a UTF-16 index and its visual affinity.
type TextInputClient ¶
type TextInputClient interface {
TextForRange(TextInputRange) (string, TextInputRange)
Selection() TextInputSelection
MarkedRange() (TextInputRange, bool)
ReplaceText(*TextInputRange, string)
SetMarkedText(*TextInputRange, string, TextInputRange)
UnmarkText()
BoundsForRange(TextInputRange) (Rect, TextInputRange, bool)
IndexForPoint(Point) (int, bool)
}
TextInputClient is an application-owned text-input target. It provides native input methods with document queries, composition and geometry; it owns the text, selection, marked range, editing policy and undo history. Pass a pointer to your client state. Callbacks run on the UI thread, as HandleInput does, and must not block on work requiring that thread. Keep the client alive across frames.
All ranges count UTF-16 code units of the current document, including its marked text. TextForRange clamps/adjusts requested ranges to valid text and returns the actual range. BoundsForRange returns element-relative geometry and the actual range represented, or false for unavailable/offscreen text. IndexForPoint takes an element-relative point and returns a UTF-16 offset.
A nil replacement range means the current marked range, if present, otherwise the selection. SetMarkedText's selected range is relative to the new marked text. ReplaceText commits and clears preedit; UnmarkText clears marked status, retaining the document's text. Selection is queried again after every mutation, before the next native event.
type TextInputRange ¶
TextInputRange is a half-open range of UTF-16 code units. These are the units of native text services and can be converted at the storage boundary. They do not prescribe the client's buffer, grapheme or selection model.
type TextInputSelection ¶
type TextInputSelection = platform.TextSelection
TextInputSelection is the primary selection reported to native input methods. Reversed places its caret at Range.Start. An editor can keep additional cursors or discontiguous ranges in its own state.
type TextKey ¶
A TextKey is a key pressed in a text input, as OnTextKey's fn sees it. It is valid while fn runs: Text and SetText panic after fn returns.
func (TextKey) SetText ¶
SetText replaces the text of the input, and its bound value, as the app does by setting the value as the view is built: a composer clears the draft it sent, Up puts the last message back. Writing the bound value from fn is not enough, as the editor writes what it holds over it.
type TextLayout ¶
type TextLayout struct {
// contains filtered or unexported fields
}
TextLayout is retained shaped text for a custom text control. It owns font and geometry results, not editable document state. Cache layouts of the paragraphs or lines you display, and replace only those affected by an edit. Its geometry methods are safe from any goroutine. Drawing uses a Painter during the view's frame. Offsets are UTF-16, matching TextInputClient.
func ShapeRichText ¶
func ShapeRichText(spans []Span, font Font, width float32) *TextLayout
ShapeRichText shapes the existing display-only Span styles into retained geometry, so an application-owned rich editor can render its own runs.
func ShapeRichTextWith ¶
func ShapeRichTextWith(spans []Span, font Font, shape TextShape) *TextLayout
ShapeRichTextWith shapes spans as ShapeRichText does, laid out as shape says: a rich text editor aligns its paragraphs.
func ShapeText ¶
func ShapeText(s string, font Font, width float32) *TextLayout
ShapeText shapes text with the system's fonts, fallback, bidi and line breaking, wrapping at width DIPs (zero only breaks at newlines). It does not retain a copy of an editor document or install keyboard/editing behavior.
func (*TextLayout) Caret ¶
func (t *TextLayout) Caret(index int) Rect
Caret gives the caret rectangle at index, snapped to a whole grapheme.
func (*TextLayout) CaretAt ¶
func (t *TextLayout) CaretAt(p TextCaretPosition) Rect
CaretAt returns the rectangle of the requested visual edge.
func (*TextLayout) IndexAt ¶
func (t *TextLayout) IndexAt(point Point) int
IndexAt finds the nearest whole-grapheme caret in visual layout order.
func (*TextLayout) Lines ¶
func (t *TextLayout) Lines() []TextLine
Lines returns the lines of the layout, from the top: where a page ends, which line holds an offset, or how many lines fit a height.
func (*TextLayout) MoveCaret ¶
func (t *TextLayout) MoveCaret(p TextCaretPosition, direction int) TextCaretPosition
MoveCaret moves one visual grapheme left (negative) or right (positive).
func (*TextLayout) NextBoundary ¶
func (t *TextLayout) NextBoundary(index int) int
func (*TextLayout) Objects ¶
func (t *TextLayout) Objects() []TextObject
Objects returns the inline objects of the layout, in the order of the text, where a rich text editor draws its attachments.
func (*TextLayout) PositionAt ¶
func (t *TextLayout) PositionAt(point Point) TextCaretPosition
PositionAt retains affinity while hit-testing whole graphemes.
func (*TextLayout) PreviousBoundary ¶
func (t *TextLayout) PreviousBoundary(index int) int
PreviousBoundary and NextBoundary find neighboring whole-grapheme offsets for logical deletion and navigation. Visual selection policy remains with the application, which can keep multiple ranges and caret affinity.
func (*TextLayout) SelectionRanges ¶
func (t *TextLayout) SelectionRanges(anchor, caret TextCaretPosition) []TextInputRange
SelectionRanges maps a visual gesture to logical UTF-16 ranges, preserving discontiguous selections through mixed-direction text. Supply these ranges to SelectionRects and to your buffer's copy/replacement operations.
func (*TextLayout) SelectionRects ¶
func (t *TextLayout) SelectionRects(ranges ...TextInputRange) []Rect
SelectionRects returns the visual rectangles of one or more logical ranges, preserving gaps in bidi selections. An editor supplies its own range set and selection policy; the layout does not reduce it to one range.
func (*TextLayout) Size ¶
func (t *TextLayout) Size() (float32, float32)
Size is the layout's extent in DIPs.
type TextLine ¶
type TextLine struct {
// Rect is the line's box: X includes the alignment and the indent,
// and W the whitespace ending the line, which the layout keeps.
Rect Rect
// Baseline is the y of the line's baseline; Ascent and Descent how
// far its fonts and objects reach above and below it.
Baseline, Ascent, Descent float32
// Start and End are the offsets of the text the line holds: a newline
// ending it is not included, and End is the next line's Start when the
// line wraps.
Start, End int
// RTL reports a line of a paragraph reading right to left.
RTL bool
}
TextLine is a line of a TextLayout, in DIPs from the layout's top-left corner and in UTF-16 offsets, as its other methods take them.
type TextLines ¶
type TextLines struct {
// contains filtered or unexported fields
}
TextLines is where a text area laid out the lines of its text, kept in the app's state with TrackLines, for an app that paints beside them: line numbers by the first row of each line where the text wraps, or marks on runs of a line. The lines are the text's, between newlines; a line the area wraps takes several rows.
The area lays out only the lines in view, and those around them: the heights of the others are estimated until it shows them, as the scroll bar's are. Between a frame's build and its layout the lines are the last frame's, in the area's last width; in Draw and DrawOver, this frame's.
func (*TextLines) AppendRows ¶
AppendRows appends where the rows of line i start to dst, as Rows.
func (*TextLines) At ¶
At returns the line at y in the content, as Top measures it: the first for y above it, the last for y past the end.
func (*TextLines) Height ¶
Height returns the height of the text: the top of the line after the last.
type TextObject ¶
TextObject is an inline object of a TextLayout (Span.ObjectWidth): the UTF-16 offset of its object replacement character, and its box, standing on its line's baseline, ObjectDescent of it below, or as far off it as its span's BaselineShift.
type TextRange ¶
TextRange styles runes Start up to End of a text input's text: their color, when its alpha is not zero, and their weight, when Weight is set, as a message field shows the mentions in what is typed.
type TextShadow ¶
type TextShadow struct {
// contains filtered or unexported fields
}
TextShadow is a shadow that text casts, as CSS's text-shadow, which NewTextShadow makes. The zero TextShadow casts none.
func NewTextShadow ¶
func NewTextShadow(x, y, blur float32, c Color) TextShadow
NewTextShadow returns the shadow of the shapes of glyphs, offset by x and y DIPs and blurred by blur, in c, for a Span's Shadow:
ui.Span{Text: "Sale", Shadow: ui.NewTextShadow(0, 2, 3, t.Accent)}
Text casts the shadows that are made, so that apps that make none do not link their painting.
type TextShape ¶
type TextShape struct {
// Width wraps lines at it, in DIPs; zero only breaks at newlines.
Width float32
// Align aligns the lines within Width: Start (the default, the right
// in right-to-left paragraphs, and of a right-to-left Direction),
// Center or End.
Align Align
// Direction is that of the element the text shows in
// (Context.Direction): right to left, lines start at the right, as
// those of Text, and paragraphs without a strongly directional
// character, as an empty one, read right to left. The others read in
// the direction of their first strong character either way.
Direction Direction
// Justify stretches every line Width wraps to Width, but the last of
// each paragraph, by widening the spaces between its words and the
// room after Han characters and kana, as printed prose sets them.
// Align places the last lines, and those with nothing to widen, as a
// word broken across lines. The whitespace ending a line hangs past
// Width.
Justify bool
// Indent moves the first line of the text this many DIPs in from the
// side its paragraph starts at, the left or the right, and wraps it
// that much narrower, as CSS's text-indent: a book indents its
// paragraphs so. The lines after a newline are not indented.
Indent float32
// NoBreakWords breaks lines only between words: a word wider than
// Width overflows it instead of breaking.
NoBreakWords bool
// Balance wraps each paragraph in lines of about the same length, at
// the narrowest width that keeps them as many as Width wraps, as
// Text's Balance does.
Balance bool
// Pretty keeps the last line of each paragraph from holding a single
// word, as Text's Pretty does.
Pretty bool
}
TextShape is how ShapeRichTextWith lays text out.
type TextSnapshot ¶
type TextSnapshot struct {
// contains filtered or unexported fields
}
TextSnapshot is an immutable, inexpensive view of a buffer. It shares unchanged chunks and can be read concurrently with further edits.
func (TextSnapshot) ByteLen ¶
func (s TextSnapshot) ByteLen() int
func (TextSnapshot) Len ¶
func (s TextSnapshot) Len() int
func (TextSnapshot) Line ¶
func (s TextSnapshot) Line(line int) string
func (TextSnapshot) LineAt ¶
func (s TextSnapshot) LineAt(index int) int
func (TextSnapshot) LineCount ¶
func (s TextSnapshot) LineCount() int
func (TextSnapshot) LineRange ¶
func (s TextSnapshot) LineRange(line int) (int, int)
LineRange returns a line's rune offsets, excluding its following newline. The terminal empty line after a newline is counted; line indices clamp.
func (TextSnapshot) RuneOffset ¶
func (s TextSnapshot) RuneOffset(index int) int
func (TextSnapshot) Slice ¶
func (s TextSnapshot) Slice(start, end int) string
func (TextSnapshot) String ¶
func (s TextSnapshot) String() string
func (TextSnapshot) TextForRange ¶
func (s TextSnapshot) TextForRange(r TextInputRange) (string, TextInputRange)
func (TextSnapshot) UTF16Len ¶
func (s TextSnapshot) UTF16Len() int
func (TextSnapshot) UTF16Offset ¶
func (s TextSnapshot) UTF16Offset(index int) int
func (TextSnapshot) Version ¶
func (s TextSnapshot) Version() uint64
type Theme ¶
type Theme struct {
Dark bool
// Background fills the window.
Background Color
// Surface is the face of buttons, inputs and other controls;
// SurfaceHover and SurfacePressed while hovered or pressed.
Surface Color
SurfaceHover Color
SurfacePressed Color
// Border outlines controls.
Border Color
// Text and TextMuted color text; TextMuted is for secondary text and
// placeholders.
Text Color
TextMuted Color
// Accent colors primary buttons, checked controls and focus rings;
// AccentText is text on it.
Accent Color
AccentHover Color
AccentPressed Color
AccentText Color
// InactiveAccent is what the accent fades to in a window that is not
// drawn as active (Context.WindowActive), as AppKit fades an inactive
// window's: the fill of selected rows, of checked check boxes, radio
// buttons and switches, of sliders and progress bars, the line of the
// selected tab and the icons of a sidebar, with AccentText on it as on
// the accent; primary buttons show as the others there. Left zero, it
// is a gray AccentText stands out on; set it to Accent to keep the
// accent in every window.
InactiveAccent Color
Danger Color
// Warning and Success color what calls for attention and what went
// well, as a Meter's levels.
Warning Color
Success Color
// Selection highlights selected text.
Selection Color
// Focus is the ring around the control with the keyboard focus,
// FocusRingWidth DIPs wide (2 by default; 0 is 2) and FocusRingOffset
// DIPs outside its edge (1 in LightTheme and DarkTheme): 0 puts the
// ring on the edge, and a negative offset inside it.
// Element.FocusRingOffset and Element.FocusRingColor change them for
// one element.
Focus Color
FocusRingWidth float32
FocusRingOffset float32
// Inverse fills tooltips and toasts, the theme turned over so that
// they stand out from what they are over: dark in a light theme, light
// in a dark one. InverseText is text on it. Left zero, they are Text
// and Background.
Inverse Color
InverseText Color
// Scrollbar colors scroll bar thumbs, ScrollbarWidth DIPs wide (6 by
// default; 0 is 6).
Scrollbar Color
ScrollbarWidth float32
// Radius rounds the corners of controls.
Radius float32
// Spacing is the unit of the room widgets leave inside and between
// their parts: their paddings and gaps, and the sizes of check boxes,
// switches, sliders and the rows of tables and trees, are multiples
// of it. 4 by default: 3 makes widgets compact, 5 roomy; 0 is 4.
Spacing float32
// FontSize is the size of text, Font its family ("" is the system's).
FontSize float32
Font string
// TooltipDelay is how long the pointer rests on an element before its
// tooltip shows (Tooltip, TooltipBase): 0 is 0.6 seconds, and a
// negative delay shows it at once. Within two thirds of it after
// another tip goes, as the pointer moves along a toolbar, the next one
// shows at once: 0.4 seconds by default.
TooltipDelay time.Duration
}
Theme holds the colors and metrics widgets use. Change a copy of LightTheme or DarkTheme and set it with Context.SetTheme.
type Timeline ¶
type Timeline struct {
// contains filtered or unexported fields
}
A Timeline plays several tweens along one playhead, so that motion that belongs together is written, controlled and tested together: a card arriving while its title fades in, rows following one another, a small bounce after the card lands. It coordinates the motion already in MyGo: a tween returns the value it shows in this frame, and the view gives it to a transform, a pose or a value, as it would give one of AnimateTo's.
card := ui.Column(c)
tl := card.Timeline("intro", ui.TimelineOptions{Run: app.opened})
x := tl.Tween(ui.Tween{From: -200, To: 0, Duration: 400 * time.Millisecond})
y := tl.Tween(ui.Tween{From: 20, To: 0, Duration: 300 * time.Millisecond},
ui.AfterPrevious(-150*time.Millisecond))
card.Translate(x, y)
An element keeps its timelines as it keeps its Keyframes, from frame to frame while the view builds it, and they go with it: build a timeline in the same order every frame, and change Run to play it again, or a changed one. A *Timeline is valid only while the view builds the frame it was returned in: ask the element for it again in the next.
func (*Timeline) Arrived ¶
Arrived is true in the one frame in which the timeline came to rest, for the view to go on, as Element.Arrived is.
func (*Timeline) Duration ¶
Duration is how long the timeline plays: the end of its last tween, without its repeats.
func (*Timeline) Label ¶
Label marks a time of the timeline for a tween to start at with AtLabel. With no placement it marks where the tween before it ends.
tl.Label("intro", ui.AtTime(0))
...
tl.Tween(ui.Tween{...}, ui.AtLabel("intro", 200*time.Millisecond))
func (*Timeline) Settled ¶
Settled reports whether the timeline rests, at its end with its repeats played out, or at its start while it plays in Reverse, as Element.Settled does for a value.
func (*Timeline) Tween ¶
Tween adds tw to the timeline where at places it, following the tween before it at once with no placement, and returns the value it shows in this frame: its From before its time, its To after it.
x := tl.Tween(ui.Tween{From: 0, To: 120, Duration: 300 * time.Millisecond})
y := tl.Tween(ui.Tween{From: 20, To: 0, Duration: 200 * time.Millisecond},
ui.AfterPrevious(-150*time.Millisecond))
type TimelineOptions ¶
type TimelineOptions struct {
// Run restarts the timeline when it changes, so that a view plays it
// again by counting: the value a callback or a piece of state gives.
Run uint64
// Repeat is how many more times the timeline plays after the first,
// RepeatForever for as long as the view builds it.
Repeat int
// Alternate plays every other time backward.
Alternate bool
// Delay holds the timeline at its first value for a while before it
// plays, and RepeatDelay the value it got to between plays.
Delay, RepeatDelay time.Duration
// Paused holds the playhead where it is, so that the time a paused
// timeline spends is not time it played and it goes on from where it
// held when it is not paused.
Paused bool
// Reverse plays the timeline backward from where the playhead is, to
// its start, as a menu that closes the way it opened; a timeline that
// Run plays over while Reverse is set plays from its end.
Reverse bool
// Seek holds the playhead at a time of the timeline, and Progress at
// a part of its duration, for a scrubber or a jump: while either is
// set the timeline does not play, and it goes on from there when it
// is not. Set one of them at most.
Seek *time.Duration
Progress *float32
// NonMotion says that the timeline's tweens move nothing on screen,
// as fades and blurs: it still plays while the desktop asks for less
// motion, as Animation's NonMotion does. Give what moves a timeline
// of its own, which goes to rest at once.
NonMotion bool
}
TimelineOptions says how a timeline plays. What it changes applies to the frame it is given in, except Run, which plays the timeline over when it changes, as KeyframeOptions.Run does.
type TitleBar ¶
type TitleBar struct{ Height, Left, Right float32 }
TitleBar is the room the window controls take at the top of a window with a hidden title bar, in DIPs: they sit in a band of Height along the top edge, Left wide from the left edge and Right wide from the right.
type Toast ¶
type Toast struct {
// ID names the toast: adding one with the ID of a toast showing
// changes that toast, which shows anew. AddToast makes one up when it
// is empty.
ID string
// Title and Description are what the toast says, which screen readers
// read out as it shows.
Title, Description string
// Type tells what kind of toast it is, as "error" or "success", for
// the look to tell.
Type string
// Timeout is how long the toast shows: 4 seconds when zero, until it
// is closed when negative. The time stops while the pointer rests on
// the toasts or the keyboard focus is in them, and runs on while the
// window is in the background or hidden: a toast whose time is over by
// the time the window shows again closes before it shows.
Timeout time.Duration
// Action labels a button that runs OnAction, as Undo after deleting,
// and closes the toast.
Action string
OnAction func()
// OnClose runs as the toast closes: its time is over, or the user, its
// action or CloseToast closed it.
OnClose func()
// Data holds what else the look of the toast needs.
Data any
}
Toast is a toast that AddToast shows, and that the view builds with ToastViewportBase to give toasts a look of its own.
type ToastParts ¶
type ToastParts struct {
Root Element
// contains filtered or unexported fields
}
ToastParts contains checked handles for the parts of a custom widget.
func ToastBase ¶
func ToastBase(c *Context, t Toast) ToastParts
ToastBase creates the toast t without a look, in the viewport of ToastViewportBase.
func (ToastParts) ActionButton ¶
func (_handle ToastParts) ActionButton() Element
ActionButton creates a button without a look, as ButtonBase does, that runs the toast's OnAction and closes it. Give it children, as the toast's Action.
func (ToastParts) CloseButton ¶
func (_handle ToastParts) CloseButton() Element
CloseButton creates a button without a look, as ButtonBase does, that closes the toast. Give it children, and a Label when they are not text.
func (ToastParts) Left ¶
func (_handle ToastParts) Left() time.Duration
Left returns how long the toast shows still, to count down, or 0 for one that shows until it is closed. It does not move while the time of the toasts stops; ask for frames with Context.AnimationFrame to draw it moving.
type Track ¶
type Track struct {
// contains filtered or unexported fields
}
Track sizes a column or a row of a grid: Fixed, Fr or FitContent, and with Min or MinContent a least size.
func FitContent ¶
func FitContent() Track
FitContent is a track as wide, or as high, as its content, within the room there is, as CSS's auto. Tracks beyond those a grid sets, such as the rows it adds for its children, fit their content.
func Fr ¶
Fr is a track taking a share f of the room the other tracks leave, as CSS's minmax(0, <f>fr): tracks of Fr(1) share it equally, even where their content is wider. Where the grid's size is not set, as the height of a grid that grows with its rows, they are as large as their content asks, in proportion to f. Min and MinContent give it a least size.
func (Track) Min ¶
Min makes the track no smaller than v DIPs, as CSS's minmax(<v>px, …): a main pane beside a side column that keeps a readable width, the grid overflowing its box rather than squeezing it.
ui.Grid(c).ColumnTracks(ui.Fr(1).Min(240), ui.Fixed(320))
An Fr track whose share of the room would be less is sized by its minimum, and the other Fr tracks share the rest, as CSS finds the size of an fr.
func (Track) MinContent ¶
MinContent makes an Fr track no smaller than the content of the items in it, their min-content widths (or heights, for a row), as CSS's minmax(auto, <f>fr), the automatic minimum CSS's plain 1fr has: a label's column that takes the room left but never cuts the label. Items spanning several tracks widen the MinContent Fr tracks among them, in proportion to their shares. Other tracks are unchanged by it.
type Transform ¶
type Transform struct {
// contains filtered or unexported fields
}
Transform is a visual transform, in 2D, or in 3D seen in perspective. Its zero value is identity. It changes drawing and interaction, leaving the space reserved by layout unchanged. Build one with Translation, Scaling, Rotation and Skewing, and in 3D TranslationZ, Translation3D, RotationX, RotationY and Perspective, and compose them with Then. Elements inherit their ancestors' transforms; each flattens what its 3D transform makes of it into its parent's plane, as CSS's flat transform-style.
func Perspective ¶
Perspective sees what the transforms before it put in 3D from distance DIPs in front of the origin, as CSS's perspective(): the shorter the distance, the deeper it looks; what goes away looks smaller. A distance of 800 or so looks natural for a card turning over.
func RotationX ¶
RotationX turns content in 3D around the horizontal axis through its origin by degrees, its top going away for positive degrees, as CSS's rotateX. Seen without Perspective after it, it only looks shorter.
func RotationY ¶
RotationY turns content in 3D around the vertical axis through its origin by degrees, its right side going away for positive degrees, as CSS's rotateY.
func Skewing ¶
Skewing slants content by x degrees along the horizontal axis and y along the vertical, as CSS's skew(x, y).
func Translation ¶
Translation moves content by x and y DIPs.
func Translation3D ¶
Translation3D moves content by x and y DIPs in its plane and z toward the viewer, as CSS's translate3d(): Translation and TranslationZ.
func TranslationZ ¶
TranslationZ moves content z DIPs along the axis toward the viewer, as CSS's translateZ(): with Perspective after it, nearer for positive z, looking larger, and farther for negative z, looking smaller, by distance/(distance-z) around the transform's origin. Without Perspective it changes nothing that shows, as in CSS. Content moved as far as Perspective's distance, or past it, is behind the viewer and shows nothing.
// 120 DIPs behind the plane, seen from 800 DIPs: 800/920 its size. ui.Box(c).Size(240, 160).Transform(ui.TranslationZ(-120).Then(ui.Perspective(800)))
type Transition ¶
type Transition uint8
Transition is how a Router's pages replace each other.
const ( // TransitionAuto slides a page in from the right going deeper, as from // "/notes" to "/notes/42", and from the left back up; pages across, as // from "/notes" to "/settings", fade in. Where the desktop asks for less // motion, they all fade. TransitionAuto Transition = iota // TransitionFade fades pages in. TransitionFade // TransitionNone shows pages at once. TransitionNone // TransitionMatch fades the page going out as the page coming fades // in, while the elements of a Transition's Match in both move from // the one to the other, as Keynote's Magic Move: a photo's thumbnail // opening into its page, its title growing into the page's heading. // Where the desktop asks for less motion, nothing moves. TransitionMatch )
type TreeItemParts ¶
type TreeItemParts struct {
Row Element
// contains filtered or unexported fields
}
TreeItemParts contains checked handles for the parts of a custom widget.
func (TreeItemParts) Depth ¶
func (_handle TreeItemParts) Depth() int
Depth returns how deep the item is: 0 at the top, 1 inside an item at the top, and so on, to indent its row by.
func (TreeItemParts) Group ¶
func (_handle TreeItemParts) Group(fn func()) Element
Group builds the items inside the item, which fn makes with the tree's Item, while it is open, in a column below the item's row. It returns the column, to style, as with a line along it, and nil while the item is closed or a leaf.
type TreeParts ¶
type TreeParts struct {
Root Element
// contains filtered or unexported fields
}
TreeParts contains checked handles for the parts of a custom widget.
func TreeBase ¶
TreeBase creates a tree without a look, as the web's role="tree": a column of items that Item makes, each a row the caller styles and fills, built inside the item it belongs to with Group. The tree is one stop of Tab, which goes to the item that had the focus last, or the one Selected; while an item has the focus, Up and Down move it to the items around, Home and End to the first and the last, Right opens the item or moves to its first child, Left closes it or moves to its parent (the other way round right to left), and typing the first letters of an item moves to it. Build the items in Root:
tree := ui.TreeBase(c)
tree.Root.Gap(2).Children(func() {
var node func(n *Node)
node = func(n *Node) {
c.Key(n.path) // the focus follows it as items above open
item := tree.Item(n.open) // nil for a leaf
item.Row.Gap(4).Padding(4, 8).PaddingStart(8 + 16*float32(item.Depth())).Radius(6)
if item.Row.FocusVisible() {
item.Row.Background(gray)
}
item.Row.Children(func() {
arrow := ui.Box(c).Size(16, 16)
if n.open != nil && arrow.Clicked() {
*n.open = !*n.open
}
ui.Text(c, n.name)
})
item.Group(func() {
for _, k := range n.children {
node(k)
}
})
}
for _, n := range app.roots {
node(n)
}
})
Tree is TreeBase with the theme's look. TreeBase builds every item that shows; for trees of thousands of items, use Outline, which builds only the rows in view, with a Prefix of your own.
func (TreeParts) Item ¶
func (_handle TreeParts) Item(open *bool) TreeItemParts
Item creates an item of the tree, at the top or, inside Group, in the item that Group is of. With a nil open it is a leaf; otherwise the items Group builds inside it show while *open is true, which Right and Left set, as does assistive technology. A key given with Context.Key just before keeps its focus on it, and on the items inside it, as items above open and close.
type Tween ¶
A Tween is a value going from From to To along Ease over Duration, which a Timeline places and plays. With no Ease it eases out (EaseOut), as an Animation does.
type UILayer ¶
type UILayer struct {
// contains filtered or unexported fields
}
UILayer is a native UI engine rendered off-window into a reusable bitmap. It has its own layout, focus, input method, scrolling and accessibility state, so the same tree can be presented by a window, a WebGPU surface, or another compositor.
Render and HandleInput run on the main thread. Render builds at most one frame; call NeedsFrame to see whether the view asked for another. The bitmap's scene is a snapshot taken by Render, so a later Render does not mutate the texture currently being presented.
func NewUILayer ¶
NewUILayer creates a native UI layer of width×height DIPs and renders its first frame.
func NewUILayerWithScale ¶
NewUILayerWithScale is NewUILayer at scale device pixels per DIP. The layer's input and Size remain in DIPs; Bitmap dimensions are device pixels.
func (*UILayer) Access ¶
func (l *UILayer) Access(name string) (AccessInfo, bool)
Access returns what assistive technology sees of the layer's last frame, by accessible name, as Tester.Access does.
func (*UILayer) AccessByRole ¶
func (l *UILayer) AccessByRole(r Role, name string) (AccessInfo, bool)
AccessByRole returns what assistive technology sees of the layer's last frame, by role and accessible name, as Tester.AccessByRole does.
func (*UILayer) Bitmap ¶
Bitmap returns the layer's bitmap for Image, Painter.Image, WebGPUCanvas.SetSource, and ImageRegion.
func (*UILayer) Close ¶
func (l *UILayer) Close()
Close drops the layer's engine and rendered resources.
func (*UILayer) Cursor ¶
Cursor returns the pointer shape the layer's hovered or focused native elements ask the presenting surface to show.
func (*UILayer) HandleInput ¶
func (l *UILayer) HandleInput(ev InputEvent) bool
HandleInput sends an input event in the layer's DIP coordinates to the layer's engine. Pointer events use the same capture, hover, focus and IME rules as input sent to a native window.
func (*UILayer) HandleSurfaceInput ¶
func (l *UILayer) HandleSurfaceInput(m SurfaceMap, ev InputEvent) bool
HandleSurfaceInput maps a pointer or wheel event from the window into the layer through m, then sends it to the layer engine. While a press is held, a move that leaves the surface keeps using the last mapped layer coordinate, so pointer capture survives deforming or clipping edges. A move back onto the surface resumes tracking its UVs. Keyboard and text events pass through without mapping.
func (*UILayer) Invalidate ¶
func (l *UILayer) Invalidate()
Invalidate asks for the layer to be rendered again.
func (*UILayer) NeedsFrame ¶
NeedsFrame reports whether the view asked for another frame.
func (*UILayer) Render ¶
func (l *UILayer) Render()
Render builds and paints one frame. It does nothing after Close.
func (*UILayer) SetScale ¶
SetScale changes the layer's backing density without changing its DIP size or input coordinates. It asks for a frame, which the host renders as usual.
func (*UILayer) TextCaret ¶
TextCaret returns where an input method composes in the layer, and whether one would, as Tester.TextCaret does.
func (*UILayer) TextInputActive ¶
TextInputActive reports whether the layer's focused element takes text and whether it turned input methods off.
func (*UILayer) TextInputClient ¶
func (l *UILayer) TextInputClient(m SurfaceMap) TextInputClient
TextInputClient bridges the layer's focused text input to the native window that presents it. The returned client translates input-method geometry through m, which is in the presenting element's coordinate space, and forwards composition and editing to the layer. Keep the returned value while the layer is presented and pass it to the presenting element's HandleTextInput.
The client captures the mapping's geometry version. Caret bounds and point queries report unavailable if the map advances without a new client, so text services never target geometry newer than the frame that created them. Build the client in the same pass as the presenting element. A nil mapping returns nil.
type UV ¶
type UV struct {
U, V float32
}
UV is a point in a surface's parameter space. U runs across the surface and V runs down it, both from 0 to 1.
type VideoDecoder ¶
type VideoDecoder interface {
// Next decodes the next frame, with io.EOF after the last.
Next() (VideoFrame, error)
// Rewind goes back to before the first frame, for the video to play
// again.
Rewind() error
}
A VideoDecoder decodes a video's frames one after another, for a VideoPlayer to show. NewGIFDecoder returns one for animated GIFs; implement one for another format. A player calls it from one goroutine at a time.
func NewGIFDecoder ¶
func NewGIFDecoder(data []byte) (VideoDecoder, error)
NewGIFDecoder returns a decoder of an animated GIF's frames, for NewVideoPlayer, as browsers show them: a frame of 10 ms or less shows for 100 ms. The GIF decodes into memory at once, its frames' pixels a byte each, and each frame is drawn as it plays. The player's SetLoop, not the GIF's loop count, says whether it plays again.
type VideoFrame ¶
type VideoFrame struct {
// Image is the picture, of any image type: the player converts it as
// Bitmap.Update does, and copies it, so the decoder may draw the next
// frame into it.
Image image.Image
// Duration is how long the frame shows; a frame of none shows for
// 100 ms, as browsers show GIFs'.
Duration time.Duration
}
A VideoFrame is a picture of a video and how long it shows.
type VideoPlayer ¶
type VideoPlayer struct {
// contains filtered or unexported fields
}
A VideoPlayer plays a video, for Video to show: its frames decode on a goroutine of its own a few ahead, as the playhead nears them, and each reaches the screen through a Bitmap's Update as it comes due, a frame passed over when the next one is due already. A new player plays as soon as a Video shows it; show it in one Video at a time. Call its methods on the main thread, in the view or an input handler, as drawing does.
func NewVideoPlayer ¶
func NewVideoPlayer(d VideoDecoder) (*VideoPlayer, error)
NewVideoPlayer returns a player of d's frames, playing. It decodes the first frame at once, which Video shows from its first frame, and which reports a video that does not decode. Make players once, not in the view, as bitmaps. Closing the player closes d if d is an io.Closer.
func (*VideoPlayer) Close ¶
func (p *VideoPlayer) Close()
Close stops decoding, and closes the decoder if it is an io.Closer, on a goroutine of its own once the frame it may be decoding is done. The video shows the frame it was at.
func (*VideoPlayer) Err ¶
func (p *VideoPlayer) Err() error
Err returns what stopped the video before its end, as a frame that did not decode: the video shows the frame before it.
func (*VideoPlayer) Loop ¶
func (p *VideoPlayer) Loop() bool
Loop reports whether the video plays again as it ends.
func (*VideoPlayer) Pause ¶
func (p *VideoPlayer) Pause()
Pause holds the video at the frame it shows.
func (*VideoPlayer) Play ¶
func (p *VideoPlayer) Play()
Play goes on from where the video was paused, or plays it again from its start once it ended.
func (*VideoPlayer) Playing ¶
func (p *VideoPlayer) Playing() bool
Playing reports whether the video plays: neither paused nor ended. It plays while out of sight too, though it does not move on then.
func (*VideoPlayer) SetLoop ¶
func (p *VideoPlayer) SetLoop(loop bool) *VideoPlayer
SetLoop plays the video again from its start each time it ends, without a gap. It returns the player.
func (*VideoPlayer) Size ¶
func (p *VideoPlayer) Size() (w, h int)
Size returns the size of the video's frames in pixels, which Video shows as DIPs.
Source Files
¶
- access.go
- access_live.go
- actions.go
- api_gen.go
- automation.go
- base.go
- bitmap.go
- cache.go
- canvas.go
- cellselect.go
- collapsible.go
- color.go
- colorpicker.go
- combobox.go
- content.go
- context.go
- data_drag.go
- date.go
- decimal.go
- diagnostics.go
- direction.go
- doc.go
- dragdrop.go
- draggable.go
- dragselect.go
- drop.go
- editable.go
- editor.go
- editor_history.go
- editor_input.go
- editor_layout.go
- editor_navigation.go
- editor_selection.go
- effect.go
- element.go
- feedback.go
- fit.go
- focus_binding.go
- focus_events.go
- focusgroup.go
- form.go
- frame.go
- framestats.go
- gif.go
- glyphs.go
- gpu_linux.go
- gpu_texture.go
- grid.go
- gridview.go
- group.go
- handler.go
- handles_debug.go
- headless.go
- indicators.go
- inline.go
- input.go
- inspector.go
- inspector_details.go
- inspector_edit.go
- inspector_editor.go
- inspector_editor_exec.go
- inspector_editor_unix.go
- inspector_gocode.go
- inspector_layout.go
- inspector_overlay.go
- inspector_panel.go
- keys.go
- layer.go
- layer_text.go
- layout.go
- layoutcache.go
- list.go
- list_builder.go
- local_close.go
- locale.go
- mask.go
- masklayers.go
- match.go
- material.go
- menu.go
- menupresentation.go
- morph.go
- motion.go
- nativeglass.go
- number.go
- outline.go
- paint.go
- path.go
- polyline.go
- popovermenu.go
- pose.go
- preferences.go
- ref.go
- repaint.go
- richtext.go
- router.go
- rowclick.go
- runtime.go
- scope.go
- scroll.go
- scrollbar.go
- selection.go
- services.go
- sidebar.go
- snap.go
- split.go
- sticky.go
- surface.go
- svg.go
- table.go
- tabs.go
- tester_access.go
- text_buffer.go
- text_input_client.go
- text_layout.go
- textarea.go
- textbuffer.go
- textbuffer_input.go
- textinput.go
- textlines.go
- textselection.go
- theme.go
- timeinput.go
- timeline.go
- toast.go
- toggle.go
- toolbar.go
- tooltip.go
- transform.go
- transition.go
- tree.go
- value_input.go
- video.go
- visibility.go
- webview.go
- wheel.go
- widecolor.go
- widgets.go
- window.go
- zindex.go
- zoom.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package chart builds charts in native UI without a look of their own, as headless libraries do on the web: scales that map data onto a plot and pick round ticks, a plot with axes around it, marks that are elements you style as any other, paths of lines, areas and pie slices for Draw functions, stacking, and a selection that the pointer and the keyboard move.
|
Package chart builds charts in native UI without a look of their own, as headless libraries do on the web: scales that map data onto a plot and pick round ticks, a plot with axes around it, marks that are elements you style as any other, paths of lines, areas and pie slices for Draw functions, stacking, and a selection that the pointer and the keyboard move. |
|
Package editor is a code editor and a diff viewer for MyGo's native UI, on package ui.
|
Package editor is a code editor and a diff viewer for MyGo's native UI, on package ui. |
|
Package shader draws with shaders an app writes: fragment shaders in Go's syntax, which run on the GPU, whichever renderer draws the window (WebGPU, Direct3D 11, OpenGL or WebGL 2), and on the CPU where none can.
|
Package shader draws with shaders an app writes: fragment shaders in Go's syntax, which run on the GPU, whichever renderer draws the window (WebGPU, Direct3D 11, OpenGL or WebGL 2), and on the CPU where none can. |