Documentation
¶
Overview ¶
Package kit is a toolkit layer over Gio for dense, keyboard-first desktop tools. It holds the primitives components are built from: theme tokens (Theme, Palette, Metrics, Strings), layout and drawing helpers, text, focus and key dispatch, scrolling, overlay layers and the App runner. The components themselves are in package kit/ui, built only from this package's exported API.
A Theme carries every color, size and string a component uses. Build one with Dark, Light, Generate or ThemeFromTokens, and restyle a subtree with Theme.Derive.
Frames follow a few rules, which the components rely on:
- Handle input before drawing: read a frame's clicks, keys and edits, update state, then lay out from that state. Hover and press state is read only inside a component's own layout callback, never before it.
- A state change made while a frame is drawn must schedule another frame. Clickable does this for clicks; call Notify for anything else.
- The UI goroutine owns all app state and themes. Work on other goroutines hands its results back with App.Post or Spawn.
- Everything interactive has a stable id (see Tag, Part and Scope), by which tests and automation find it. Ids never key state and are never the spoken label.
Index ¶
- Constants
- func Border(gtx layout.Context, rect image.Rectangle, r, w int, c color.NRGBA)
- func Box(gtx layout.Context, size unit.Dp, s Surface, w layout.Widget) layout.Dimensions
- func Col(gtx layout.Context, children ...layout.FlexChild) layout.Dimensions
- func Contrast(a, b color.NRGBA) float64
- func EaseInOut(t float32) float32
- func EaseOut(t float32) float32
- func EaseOutBack(t float32) float32
- func EscapeID(s string) string
- func Fill(gtx layout.Context, c color.NRGBA, w layout.Widget) layout.Dimensions
- func Fixed(width unit.Dp, w layout.Widget) layout.Widget
- func Flexed(weight float32, w layout.Widget) layout.FlexChild
- func Flow(gtx layout.Context, hgap, vgap unit.Dp, children ...layout.Widget) layout.Dimensions
- func FocusID(gtx layout.Context, tag event.Tag, id string)
- func FocusWithin(gtx layout.Context, w layout.Widget) (layout.Dimensions, bool)
- func FormatChord(n key.Name, m key.Modifiers) string
- func Gap(w, h unit.Dp) layout.Widget
- func Group(gtx layout.Context, id, label string, role Role, w layout.Widget) layout.Dimensions
- func Grow(gtx layout.Context) layout.Dimensions
- func HLine(c color.NRGBA) layout.Widget
- func Hex(c color.NRGBA) string
- func IconAlert(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconArrowDown(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconCheck(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconChevronDown(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconChevronLeft(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconChevronRight(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconChevronUp(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconCircleCheck(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconCircleX(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconInfo(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconLayout(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconMenu(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconMinus(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconMore(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconPlus(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconSearch(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconSettings(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconSun(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func IconX(gtx layout.Context, size unit.Dp, c color.NRGBA) layout.Dimensions
- func KeyContext(gtx layout.Context, name string, w layout.Widget) layout.Dimensions
- func Layer(gtx layout.Context, offset image.Point, w layout.Widget)
- func Lerp(a, b, t float32) float32
- func LerpColor(a, b color.NRGBA, t float32) color.NRGBA
- func Lighten(c color.NRGBA, d uint8) color.NRGBA
- func Linear(t float32) float32
- func Loop(gtx layout.Context, period time.Duration) float32
- func Luminance(c color.NRGBA) float64
- func Main()
- func Notify(gtx layout.Context)
- func OnAction(gtx layout.Context, action ActionID, run func())
- func Pad(v, h unit.Dp, w layout.Widget) layout.Widget
- func ParseChord(s string) (key.Name, key.Modifiers, error)
- func ParseHex(s string) (color.NRGBA, error)
- func Part(id string, names ...string) string
- func Path(gtx layout.Context, id string) string
- func Rigid(w layout.Widget) layout.FlexChild
- func Row(gtx layout.Context, children ...layout.FlexChild) layout.Dimensions
- func Scope(gtx layout.Context, name string, w layout.Widget) layout.Dimensions
- func Stretch(w layout.Widget) layout.Widget
- func Tag(gtx layout.Context, id string)
- func TagArea(gtx layout.Context, id string, w layout.Widget) layout.Dimensions
- func TagImage(gtx layout.Context, id, label string)
- func TagLabel(gtx layout.Context, id, label string)
- func TextInput(gtx layout.Context, e *widget.Editor)
- func TraceEnabled() bool
- func Tracef(kind string, kv ...any)
- func VLine(c color.NRGBA) layout.Widget
- func WithAlpha(c color.NRGBA, a uint8) color.NRGBA
- type Action
- type ActionID
- type Actions
- type AnchoredList
- type App
- type Binding
- type Clickable
- func (c *Clickable) Anim() *Tween
- func (c *Clickable) Click()
- func (c *Clickable) Clicked(gtx layout.Context) bool
- func (c *Clickable) Focus(gtx layout.Context)
- func (c *Clickable) FocusQuiet(gtx layout.Context)
- func (c *Clickable) FocusTag() event.Tag
- func (c *Clickable) Hovered() bool
- func (c *Clickable) Layout(gtx layout.Context, w layout.Widget) layout.Dimensions
- func (c *Clickable) Modifiers() key.Modifiers
- func (c *Clickable) Pressed() bool
- type Column
- type ControlSize
- type Dialog
- type DrawCache
- type Easing
- type EditorField
- type Flex
- type Focus
- type FocusGroup
- func (g *FocusGroup) Focus(gtx layout.Context)
- func (g *FocusGroup) FocusHandle() *Focus
- func (g *FocusGroup) FocusQuiet(gtx layout.Context)
- func (g *FocusGroup) HasFocus(gtx layout.Context) bool
- func (g *FocusGroup) Join(c *Clickable, active bool)
- func (g *FocusGroup) Layout(gtx layout.Context, id string, w layout.Widget) layout.Dimensions
- func (g *FocusGroup) RingVisible(gtx layout.Context) bool
- type FocusVisible
- type Fonts
- type FrameStats
- type HoverArea
- type Icon
- type Image
- type Keymap
- func (k *Keymap) Attach(gtx layout.Context)
- func (k *Keymap) Bind(spec, title string, run func()) error
- func (k *Keymap) BindActions(a *Actions, defaults map[string]string, overrides []byte) error
- func (k *Keymap) Bindings() []Binding
- func (k *Keymap) Hint(title string) string
- func (k *Keymap) HintFor(actionID string) string
- func (k *Keymap) MustBind(spec, title string, run func())
- type List
- type MenuRow
- type Metrics
- type OKLCH
- type Palette
- type Pool
- type Popup
- type Role
- type Seed
- type State
- type Status
- type Strings
- type Surface
- type Table
- type Task
- type TextSpan
- type Theme
- func Black() *Theme
- func CatppuccinFrappe() *Theme
- func CatppuccinLatte() *Theme
- func CatppuccinMacchiato() *Theme
- func CatppuccinMocha() *Theme
- func Dark() *Theme
- func Generate(s Seed) *Theme
- func Light() *Theme
- func New(p Palette) *Theme
- func Pink() *Theme
- func Presets() []*Theme
- func ThemeFromTokens(data []byte, base *Theme) (*Theme, error)
- func (t *Theme) AnchoredList(gtx layout.Context, a *AnchoredList, id string, ids []string, ...) layout.Dimensions
- func (t *Theme) Bar(gtx layout.Context, v, h unit.Dp, w layout.Widget) layout.Dimensions
- func (t *Theme) Caption(gtx layout.Context, s string) layout.Dimensions
- func (t *Theme) Card(gtx layout.Context, w layout.Widget) layout.Dimensions
- func (t *Theme) Code(gtx layout.Context, s string, size unit.Sp, c color.NRGBA) layout.Dimensions
- func (t *Theme) CodeBlock(gtx layout.Context, s string, size unit.Sp, c color.NRGBA) layout.Dimensions
- func (t *Theme) ControlPad(size ControlSize, v unit.Dp) unit.Dp
- func (t *Theme) Derive(f func(t *Theme)) *Theme
- func (t *Theme) Disable(gtx layout.Context, disabled bool, w layout.Widget) layout.Dimensions
- func (t *Theme) Dur(d time.Duration) time.Duration
- func (t *Theme) EditorField(gtx layout.Context, e *widget.Editor, id string, f EditorField) layout.Dimensions
- func (t *Theme) Field(gtx layout.Context, st State, w layout.Widget) layout.Dimensions
- func (t *Theme) FieldPad(size ControlSize) unit.Dp
- func (t *Theme) FloatingPanel(gtx layout.Context, content layout.Widget) layout.Dimensions
- func (t *Theme) FocusRing(gtx layout.Context, sz image.Point, r int)
- func (t *Theme) Heading(gtx layout.Context, s string) layout.Dimensions
- func (t *Theme) Highlight(lit float32) color.NRGBA
- func (t *Theme) List(gtx layout.Context, l *List, id string, n int, item layout.ListElement) layout.Dimensions
- func (t *Theme) MenuRow(gtx layout.Context, c *Clickable, id string, r MenuRow) layout.Dimensions
- func (t *Theme) MenuRowWidth(gtx layout.Context, r MenuRow) int
- func (t *Theme) MissingGlyphs(s string) []rune
- func (t *Theme) Modal(gtx layout.Context, d *Dialog, id string, page layout.Widget, ...) layout.Dimensions
- func (t *Theme) Paragraph(gtx layout.Context, s string, c color.NRGBA) layout.Dimensions
- func (t *Theme) ParagraphLine(gtx layout.Context, s string, c color.NRGBA, w font.Weight) layout.Dimensions
- func (t *Theme) Pill(gtx layout.Context, s string, fg, bg color.NRGBA) layout.Dimensions
- func (t *Theme) Popover(gtx layout.Context, p *Popup, id string, anchor layout.Widget, ...) layout.Dimensions
- func (t *Theme) Press(gtx layout.Context, c *Clickable, id string, ...) layout.Dimensions
- func (t *Theme) Progress(gtx layout.Context, value float32) layout.Dimensions
- func (t *Theme) RadiusFull() unit.Dp
- func (t *Theme) RadiusLg() unit.Dp
- func (t *Theme) RadiusSm() unit.Dp
- func (t *Theme) Required(id, value string) Validation
- func (t *Theme) SizedField(gtx layout.Context, size ControlSize, st State, w layout.Widget) layout.Dimensions
- func (t *Theme) Space(v unit.Dp) unit.Dp
- func (t *Theme) Spinner(gtx layout.Context, size unit.Dp) layout.Dimensions
- func (t *Theme) StateColor(base color.NRGBA, st State) color.NRGBA
- func (t *Theme) StatusColors(s Status) (fg, bg color.NRGBA, icon Icon)
- func (t *Theme) Styled(s Surface) Surface
- func (t *Theme) StyledText(gtx layout.Context, spans ...TextSpan) layout.Dimensions
- func (t *Theme) Text(gtx layout.Context, s string, size unit.Sp, c color.NRGBA, w font.Weight) layout.Dimensions
- func (t *Theme) Tint(c color.NRGBA, amount float32) color.NRGBA
- func (t *Theme) Tokens() ([]byte, error)
- func (t *Theme) UseFonts(f Fonts)
- func (t *Theme) WithLabel(gtx layout.Context, label string, ctl layout.Widget) layout.Dimensions
- type TokenError
- type Transition
- type Tween
- func (tw *Tween) From(gtx layout.Context, v float32, d time.Duration)
- func (tw *Tween) Running(gtx layout.Context) bool
- func (tw *Tween) To(gtx layout.Context, target float32, d time.Duration) float32
- func (tw *Tween) ToEase(gtx layout.Context, target float32, d time.Duration, e Easing) float32
- func (tw *Tween) Value(gtx layout.Context) float32
- type TypeScale
- type UnknownActionsError
- type Validation
- type Window
Constants ¶
const ( // ContrastText is Fg's target: WCAG AAA for normal text (7:1). ContrastText = 7.0 // ContrastMuted is Muted's target, a clear step above Dim. ContrastMuted = 6.5 // ContrastAA is the target of Dim, accent and status text: WCAG AA for // normal text (4.5:1), which also exceeds AA for large text (3:1). ContrastAA = 4.5 )
WCAG 2.x contrast targets. Legible enforces the text targets; WithContrast raises them and adds the non-text one.
const ( RoleButton = semantic.Button RoleLink = semantic.Link RoleCheckbox = semantic.CheckBox RoleSwitch = semantic.Switch RoleRadio = semantic.RadioButton RoleTextbox = semantic.Editor RoleSlider = semantic.Slider RoleCombobox = semantic.ComboBox RoleListbox = semantic.ListBox RoleOption = semantic.Option RoleList = semantic.List RoleListItem = semantic.ListItem RoleTree = semantic.Tree RoleTreeItem = semantic.TreeItem RoleGrid = semantic.Grid RoleRow = semantic.Row RoleGridCell = semantic.GridCell RoleTabList = semantic.TabList RoleTab = semantic.Tab RoleMenu = semantic.Menu RoleMenuItem = semantic.MenuItem RoleDialog = semantic.Dialog RoleImage = semantic.Image RoleToolbar = semantic.Toolbar RoleStatus = semantic.Status // a toast, a live message RoleTooltip = semantic.Tooltip RoleGroup = semantic.Group RoleSeparator = semantic.Separator )
The roles kit's components record.
const ( Space0p5 unit.Dp = 2 Space1 unit.Dp = 4 Space1p5 unit.Dp = 6 Space2 unit.Dp = 8 Space2p5 unit.Dp = 10 Space3 unit.Dp = 12 Space3p5 unit.Dp = 14 Space4 unit.Dp = 16 Space5 unit.Dp = 20 Space6 unit.Dp = 24 Space8 unit.Dp = 32 Space10 unit.Dp = 40 Space12 unit.Dp = 48 )
The spacing scale, GPUI/Tailwind style: SpaceN is N×4dp, with half steps spelled 0p5, 1p5, 2p5, 3p5. Use these instead of hand-picked dp values; pass them through Theme.Space (or kit.Flex, which does it) so Density applies.
const ( SizeCaption unit.Sp = 11 // uppercase section labels, column headers SizeSmall unit.Sp = 12 SizeBody unit.Sp = 13 SizeText unit.Sp = 14 SizeStat unit.Sp = 20 SizeTitle unit.Sp = 22 )
Default type scale (also exposed as the Size* constants).
const ( DurFast = 90 * time.Millisecond // hover and press tints DurNormal = 160 * time.Millisecond // toggles, indicators, page transitions DurSlow = 260 * time.Millisecond // larger movement )
Standard durations (before Motion scaling).
const ( Regular = font.Normal Medium = font.Medium SemiBold = font.SemiBold Bold = font.Bold )
Font weights for Theme.Text and Theme.HeadingWeight, so callers need not import gioui.org/font.
const PressTint = 0.16
PressTint is how far a pressed control's fill moves toward Fg (hover goes half way).
Variables ¶
This section is empty.
Functions ¶
func Border ¶
Border fills a w-px rounded border just inside rect (radius r). It is a filled ring (outer contour minus inner contour), not a clip.Stroke: Gio re-flattens strokes on the CPU every frame, which was over half the frame time on control-heavy pages. Use it for every outline; r = height/2 makes pills and circles.
func Box ¶
Box draws a fixed square (fill + border) and centers w inside it. Use it for checkboxes and icon buttons; it never collapses to its content.
func Contrast ¶
Contrast is the WCAG 2.x contrast ratio of two opaque colors, from 1 to 21, in either order. See ContrastAA and ContrastText for the targets.
func EaseInOut ¶
EaseInOut accelerates, then decelerates (cubic): for motion between two resting places, such as a sliding indicator.
func EaseOutBack ¶
EaseOutBack overshoots slightly before settling: good for toggles and pops.
func Fixed ¶
Fixed constrains w to an exact width. A width of 0 (or less) keeps the incoming width constraints.
func Flexed ¶
Flexed is layout.Flexed: a flex child given weight's share of the space left after the rigid children.
func Flow ¶
Flow lays children out left to right, wrapping onto new lines when the width runs out, like words in a paragraph (diff tokens, chips, tags). Each line is as tall as its tallest child; children top-align. hgap and vgap separate children on a line and the lines; they are used as given, not scaled by Density: pass th.Space(kit.SpaceN) for themed spacing.
func FocusID ¶
FocusID declares that the focusable tag is the control id this frame. It does two things, and every focusable needs both:
- it names what holds focus, for kittest's FocusedID and inspectors;
- it records tag in the current KeyContext, so while tag is focused, keys it leaves unclaimed resolve against the actions and keymaps of the contexts enclosing it.
kit's components call it. A custom focusable (a key.FocusFilter on its own tag: a slider, a split handle) calls it beside its Tag, inside the KeyContext whose actions should apply. If tag is registered more than once in a frame, the first registration wins: its id and its KeyContext.
func FocusWithin ¶
FocusWithin lays out w inside a KeyContext of its own and reports whether something w recorded as focusable (with FocusID, a Focus or a Clickable) holds keyboard focus: CSS :focus-within. A tooltip uses it to show while its control is focused. Actions w declares at its top level apply while that focus is inside.
func FormatChord ¶
FormatChord renders a chord for display, with platform names (Shortcut → Cmd on macOS, Ctrl elsewhere). Keys Gio names with symbols the bundled fonts lack (⌦, ⇱) are written as words, as ParseChord spells them, so the result parses back.
func Group ¶
Group names a region: id for tests, label for screen readers, role (RoleGroup, RoleToolbar, RoleStatus...; 0 for none), sized to what w draws.
func Grow ¶
func Grow(gtx layout.Context) layout.Dimensions
Grow is a flexible spacer for a Row: in layout.Flexed it claims all the width it is given, so the children after it are pushed to the end. It claims no height, so in a vertical flex use a Flexed Gap instead.
func HLine ¶
HLine draws a 1dp horizontal rule in c across the available width: a divider, which unlike control borders does not follow Theme.Stroke.
func IconArrowDown ¶
IconArrowDown is a downward arrow: download, or sort descending.
func IconChevronDown ¶
IconChevronDown is a downward chevron: opens a dropdown or expands a section.
func IconChevronLeft ¶
IconChevronLeft is a leftward chevron: back navigation.
func IconChevronRight ¶
IconChevronRight is a rightward chevron: a collapsed section or forward navigation.
func IconChevronUp ¶
IconChevronUp is an upward chevron: collapses a section.
func IconCircleCheck ¶
IconCircleCheck is a check mark in a circle: success.
func IconCircleX ¶
IconCircleX is a cross in a circle: an error.
func IconLayout ¶
IconLayout is a split rectangle: a layout or panes.
func IconSearch ¶
IconSearch is a magnifying glass: search.
func IconSettings ¶
IconSettings is a gear: settings or preferences.
func KeyContext ¶
KeyContext lays out w inside a named dispatch node. Actions and keymaps declared inside apply while focus is anywhere within it; nested contexts are asked first. Popups lay out inside their opener's context, so a menu opened from an editor still reaches the editor's handlers.
func Layer ¶
Layer draws w above everything else in the window, offset from the current origin: it records w and defers the recording with op.Defer. Tooltips, toasts and other floating content use it rather than op.Defer directly. w is laid out with the current constraints; it gets no input priority beyond being drawn last.
func Loop ¶
Loop returns the phase (0..1) of a continuous animation with the given period, and schedules the next frame. With period 0 (Motion = 0) it returns 0 and schedules nothing: draw a static frame.
Unlike a Tween it is never finished, so it must not keep kittest's Settle busy. It asks for a redraw at "this frame's time + 1ns". In a real window that moment has passed by the time Gio checks, so Gio animates at vsync, the same pacing Tween's immediate requests get; a later time would switch Gio to timer pacing (docs/pitfalls.md #20). Settle compares against its virtual clock, sees a future time and doesn't chase it, so a UI with a spinner still settles.
func Luminance ¶
Luminance is WCAG 2.x relative luminance, from 0 (black) to 1 (white), ignoring alpha.
func Main ¶
func Main()
Main hands the main goroutine to the platform's event loop (Gio's app.Main). Call it at the end of main, after starting App.Run on another goroutine. It does not return on every platform, so deferred calls in main may never run: exit from the goroutine that ran Run.
func Notify ¶
Notify schedules a redraw (GPUI: cx.notify). Call it after mutating state mid-frame so everything drawn earlier in the frame catches up immediately.
func OnAction ¶
OnAction handles action while focus is inside the current KeyContext (or anywhere, at the top level). The nearest handler to the focus wins. run is called after layout; the frame is redrawn afterwards.
func ParseChord ¶
ParseChord parses "Ctrl+Shift+P" into Gio's key name and modifiers. Names are case-insensitive. The plus key is written "+" ("Ctrl++"). For a physical key code ("KeyQ") the name is what the current layout types with it. It fails on an unknown modifier or key, a missing key, and function keys Gio does not deliver (F0, F13 and above).
func ParseHex ¶
ParseHex parses a color written as #rgb, #rrggbb or #rrggbbaa, in either case; the leading # is optional. It returns the zero color and an error naming the input when s is not one of those forms.
func Part ¶
Part is the id of a named part inside the component with id, one segment per name: Part("lang", "opt", "3") is "lang/opt/3".
func Path ¶
Path is the full id for a local id at this point of the layout: the current Scope, then id. Empty ids stay empty.
func Scope ¶
Scope lays out w with name appended to the id path, so ids inside need not know their context and two instances of a composite never collide.
Ids are paths. A component gets a local id from its caller; the parts it creates inside (a field, an option, a row) are Part(id, name), and Scope prefixes everything laid out within it. Tag emits the full path:
kit.Scope(gtx, "invoice:42", func(gtx layout.Context) layout.Dimensions {
return ui.Button{ID: "pay", Text: "Pay", Style: ui.Solid}.Layout(gtx, th, &v.pay) // id "invoice:42/pay"
})
"/" separates levels; ":" is free for "kind:record" names. Part and Scope escape their segments, so record ids may contain anything.
Ids name things for tests and automation only. They never key state (that is the caller's struct or a Pool keyed by the local id), so moving a widget into a scope does not lose its state, and they are never the spoken label. Without a kit.Window frame, Scope adds nothing.
func Tag ¶
Tag attaches a semantic description to the current clip area: the stable id tests find widgets by, and what screen readers announce. Use "kind:recordID".
func TagArea ¶
TagArea lays out w on a clip area of its own, as large as w, and gives that area the id: for content that has no area to Tag (a label, a drawing).
func TagImage ¶
TagImage names an image area: id for tests, label as its alternative text, role RoleImage. Audits treat the label as a description, not painted text.
func TagLabel ¶
TagLabel gives an addressed control a human-readable semantic label. The id remains stable for automation; the label can change with localization or state. Use this for icon-only controls and custom-drawn controls.
func TextInput ¶
TextInput declares e, laid out this frame, a text input. Components that draw an editor their own way (a code entry drawn as boxes, an editor kept invisible behind custom text) call it each frame they lay it out; EditorField does it for its own. While e has focus, keymaps leave printable keys to it, so typing never runs single-key shortcuts, and keys it leaves resolve from the KeyContext it was laid out in.
func Tracef ¶
Tracef writes one GIOKIT_TRACE line; it is a no-op without GIOKIT_TRACE. Every line reads
giokit <ms since start> f<frame> <kind> key=value ...
kv alternates keys and values; a trailing key without a value is dropped. float32 values print with 2 decimals, float64 with 3. kit/forktrace routes the Gio fork's window events (wl_*, scroll_flush, gpu_frame, present) here, so one log interleaves them with kit's frame pacing and list state, in order. Safe from any goroutine.
Types ¶
type Action ¶
type Action struct {
ID string // stable identifier; keymap files refer to it
Title string // display name, shown in menus and palettes
Category string // groups actions in menus and palettes ("File", "View"); searched too
Description string // a longer explanation for palettes and help
Run func() // the command, on the UI goroutine; must not be nil
Enabled func() bool // nil means enabled
}
Action is one named application command shared by shortcuts, menus and palettes ("file.save", "view.zoom_in"). It is distinct from ActionID, which names what a focused control does with a key (move, expand) and is resolved through KeyContexts.
type ActionID ¶
type ActionID string
ActionID names a key action: something the focused control does (move, expand, confirm), resolved through the KeyContexts around the focus. Components declare the actions they handle with OnAction, and the default keymap binds chords to them.
It is distinct from Action, a named application command listed in menus and palettes and bound to chords with Keymap.BindActions.
const ( ActMoveUp ActionID = "ui.move_up" ActMoveDown ActionID = "ui.move_down" ActFirst ActionID = "ui.first" ActLast ActionID = "ui.last" ActExpand ActionID = "ui.expand" // Right: open a tree node, or go to its first child ActCollapse ActionID = "ui.collapse" // Left: close a tree node, or go to its parent ActConfirm ActionID = "ui.confirm" // Enter: pick the active item ActCancel ActionID = "ui.cancel" // Escape: close the innermost popup or dialog ActExtendUp ActionID = "ui.extend_up" // Shift+Up: grow a multiple selection upward ActExtendDown ActionID = "ui.extend_down" // Shift+Down: grow it downward ActSelectAll ActionID = "ui.select_all" // Ctrl/Cmd+A: select every item // ActContextMenu is Shift+F10: open the context menu of the focused // control (the keyboard's right click). ActContextMenu ActionID = "ui.context_menu" )
Built-in actions, bound by the default keymap.
type Actions ¶
type Actions struct {
// contains filtered or unexported fields
}
Actions is a registry of commands, in registration order. The zero value is an empty registry. Register every action up front; menus, palettes and Keymap.BindActions read it. An Actions belongs to the UI goroutine; Run and Enabled functions are called there.
func (*Actions) List ¶
List returns every action, enabled or not, in registration order. It returns a copy: changing it does not change a.
func (*Actions) MustRegister ¶
MustRegister is Register for actions written in code; it panics on error.
func (*Actions) Register ¶
Register adds action. It fails when the id, title or Run is missing, or when the id is already registered.
func (*Actions) Run ¶
Run runs the action with this id if it exists and is enabled, and reports whether it ran.
func (*Actions) Search ¶
Search returns the enabled actions matching query, best first: the title starting with it, then a word of the title starting with it, then the title, category or id containing it, then its letters in order ("gtp" finds "Go to page"). An empty query lists every enabled action in registration order. Matching ignores case.
type AnchoredList ¶
type AnchoredList struct {
// List is the scroll state; read or set its Position as for any List.
List List
// contains filtered or unexported fields
}
AnchoredList keeps the first visible item, by stable id, at the same screen offset when items are inserted, removed, or reordered. It suits chat history and live feeds, where index-based scroll positions would jump. The zero value is ready to use. Its List identifies input areas by address, so an AnchoredList must not be copied after first use.
type App ¶
type App struct {
// ID is the Wayland app_id and X11 class; match StartupWMClass in the
// app's .desktop file.
ID string
// Title is the window title.
Title string
// Width and Height are the initial window size.
Width, Height unit.Dp
// Background, if not transparent, fills the whole window before each
// frame, including the strips under system bars that frames never
// reach: on phones, frame's gtx covers only the safe area inside the
// status and navigation bars and any display cutout, and the strips
// outside it would show white. It is also the colour of Android's
// status and navigation bars where the system draws them opaque, with
// their icons dark or light to suit. Read every frame, so it may change.
Background color.NRGBA
// Fullscreen opens the window fullscreen. On Android it hides the status
// and navigation bars, which a swipe from an edge shows for a moment.
Fullscreen bool
// OnPanic, if set, receives a panic from a Post callback (Spawn's done
// included) instead of letting it crash the program; the other queued
// callbacks still run. Log it and keep going, or show an error.
OnPanic func(recovered any)
// contains filtered or unexported fields
}
App runs a single-window program. All app state belongs to the UI goroutine (GPUI: the main thread owns entities); other goroutines go through Post and Spawn.
Create an App with NewApp: the zero App has no window and is not usable. An App runs one window once; set its fields before calling Run.
func NewApp ¶
NewApp returns an App for a window titled title, of initial size w by h, with id as its Wayland app_id and X11 class (see App.ID). The window opens when Run is called.
func (*App) Drain ¶
func (a *App) Drain()
Drain runs pending posts. Run calls it each frame; harnesses may call it too.
func (*App) Focused ¶
Focused reports whether the window has keyboard focus. Input that isn't routed through the window, such as gamepads (kit/pad), checks it so a background window doesn't react. It is safe from any goroutine.
func (*App) Invalidate ¶
func (a *App) Invalidate()
Invalidate requests a frame. Safe from any goroutine: wire a paint.Stream's OnFrame to it so new video frames get drawn.
func (*App) LastFrame ¶
func (a *App) LastFrame() FrameStats
LastFrame returns the figures for the last frame drawn; zero before the first. Call it from the UI goroutine, in a frame, to show the previous frame's figures.
func (*App) Pending ¶
Pending reports Spawn work still running (not yet posted back to the UI goroutine). Harnesses wait for it to reach 0.
func (*App) Post ¶
func (a *App) Post(f func())
Post runs f on the UI goroutine before the next frame, and triggers that frame. It never blocks, so it is safe from the UI goroutine too (a post made while draining runs in the next frame). The queue is unbounded: a producer that outruns the frame rate should coalesce its updates itself.
func (*App) Queued ¶
Queued reports callbacks posted with Post (Spawn's done included) that have not run yet. A window draws a frame for each; a harness that drives frames itself keeps drawing while Queued is above 0. Safe from any goroutine.
func (*App) Quit ¶
func (a *App) Quit()
Quit closes the window, which makes Run return. Safe from any goroutine.
func (*App) Run ¶
Run opens the window and calls frame for every frame, on the calling goroutine, which becomes the UI goroutine. It returns once the window has closed (by the user or Quit), with the window's error, or nil after a normal close. Run it on its own goroutine and hand the main goroutine to Main; when Run returns, save state and exit the process:
go func() {
if err := a.Run(v.Frame); err != nil {
log.Fatal(err)
}
os.Exit(0)
}()
kit.Main()
Set GIOKIT_TRACE=1 to log frame pacing to stderr: one line per second with frame count, interval stats and build time, plus a line for every frame that arrived late (> 1.5× the median interval). Use it to diagnose stutter the headless harness can't see (compositor pacing, vsync, scaling).
type Binding ¶
type Binding struct {
// Chord is the chord in display form, as FormatChord writes it, whatever
// spelling was passed to Bind: binding "ctrl+k" gives "Ctrl+K". A
// physical key shows what the current layout types with it ("KeyQ" is
// "A" on AZERTY); Bindings, Hint and HintFor give it fresh.
Chord string
Title string // human description, for menus / palettes / help
// Action is the id of the Action this binding runs, when BindActions
// made it; "" for bindings made with Bind.
Action string
Run func() // what the chord does, on the UI goroutine
// contains filtered or unexported fields
}
Binding is one chord → function.
type Clickable ¶
type Clickable struct {
// FocusOnClick focuses the clickable when clicked, without showing the
// focus ring until the keyboard is used (list items: so arrow keys work
// right after a click).
FocusOnClick bool
// contains filtered or unexported fields
}
Clickable is a pressable area that notifies whenever it reports a click. It is keyboard-focusable: Tab reaches it, Enter/Space click it. Inside a FocusGroup it is not a Tab stop of its own; the group is.
kit owns this rather than wrapping widget.Clickable, because Gio puts every tag that asks for focus events into the Tab order and widget.Clickable always asks.
The zero value is ready to use. A Clickable is its own event tag (and its FocusGroup refers to it by address), so it must not be copied or moved after its first Layout: keep it in a struct field or a Pool, not in a slice that grows. Like all kit state it belongs to the UI goroutine.
func (*Clickable) Anim ¶
Anim is a per-control animation slot for the component drawing c (a switch's thumb, a radio's dot): animate it with Tween.To or ToEase.
func (*Clickable) Click ¶
func (c *Clickable) Click()
Click queues a programmatic click, reported by the next Clicked.
func (*Clickable) Clicked ¶
Clicked reports a click since the last call, and consumes it: each click is reported once. A click also focuses the group (inside a FocusGroup) or the clickable (with FocusOnClick), and schedules a redraw. Call it in your handle pass, before the widget is laid out: Layout consumes and drops pending clicks. It reports at most one click per call.
A clickable laid out disabled (Theme.Disable) reports nothing and doesn't even ask for events: asking is what makes Gio deliver clicks and put it in the Tab order.
func (*Clickable) Focus ¶
Focus gives c keyboard focus, with its ring shown (e.g. the first field of a dialog).
func (*Clickable) FocusQuiet ¶
FocusQuiet gives c focus without showing the ring until the keyboard is used (returning focus to a menu's trigger after a mouse pick).
func (*Clickable) FocusTag ¶
FocusTag is the tag Gio routes this clickable's focus and key events to.
func (*Clickable) Layout ¶
Layout lays out w and makes its bounds the clickable's press and focus area, with no hover or press drawing of its own (Theme.Press adds those, and the id and role). Clicks that arrived since the last Clicked call are dropped: read them with Clicked in the handle pass, before Layout.
type Column ¶
type Column struct {
Title string // the header text, drawn as a caption
Width unit.Dp // fixed width; 0 shares the leftover space
// Align places each cell's content: layout.W or layout.E. The zero
// value, layout.NW, also means W (cells are one line, so NW and W look
// the same).
Align layout.Direction
}
Column describes one table column. Width 0 means flexible (shares leftover space).
type ControlSize ¶
type ControlSize int
ControlSize is the height class of controls: Theme.Controls for the whole theme, a component's Size for one instance.
const ( ControlDefault ControlSize = iota // on a component: the theme's size; on a theme: medium ControlSmall ControlMedium ControlLarge )
Control sizes. ControlDefault is the zero value, so a component without a Size follows its theme, and a theme without Controls is medium. Any value other than these is treated as medium.
type Dialog ¶
type Dialog struct {
// Persistent dialogs ignore Escape and backdrop clicks: only your
// buttons close them (unsaved-changes prompts).
Persistent bool
// contains filtered or unexported fields
}
Dialog is the state of a modal dialog (th.Modal). Open it with Show from your handle pass. The zero value is closed. Like Popup, it identifies its areas by address: do not copy one after first use.
func (*Dialog) DidDismiss ¶
DidDismiss reports whether the user closed the dialog with Escape or a backdrop click since the last call (your buttons call Hide themselves).
type DrawCache ¶
type DrawCache[K comparable] struct { // contains filtered or unexported fields }
DrawCache records drawing once and replays it on later frames until its key changes, so the GPU reuses the geometry instead of rebuilding it.
The renderer keeps a filled shape's vertex buffer only while the operation that drew it is the same one, in the same op list; the frame's list is reset every frame, so a clip.Outline or clip.Path drawn straight into gtx.Ops is flattened and uploaded again every frame (a GPU buffer per shape, plus garbage for the collector). Replaying a DrawCache's recording is the same operation each time and hits the cache. The cache key ignores translation, so a recording replayed under op.Offset at a new position each frame (a sprite's shadow in flight) still hits; scaling, rotation and shear re-flatten.
Use it for drawing that changes rarely: backgrounds, decorations, text drawn as shapes, anything whose inputs fit a comparable key. Draw only: input handlers recorded inside are replayed as recorded, with whatever state they captured, so keep clickables and tags outside.
The zero value is empty and records on first use. A DrawCache belongs to the UI goroutine and must not be copied after first use.
func (*DrawCache[K]) Draw ¶
Draw adds the recording to gtx.Ops, first recording it with draw when the cache is empty or was recorded with a different key. draw gets gtx with its Ops replaced by the cache's own list; everything else is as passed.
func (*DrawCache[K]) Invalidate ¶
func (c *DrawCache[K]) Invalidate()
Invalidate empties the cache, so the next Draw or Record records again whatever the key.
type EditorField ¶
type EditorField struct {
Placeholder string // dim hint drawn while the editor is empty
Label string // spoken name; default Placeholder
Size ControlSize // height class; ControlDefault is the theme's
Icon Icon // optional, before the text
// Lines is the minimum height in lines; 0 is one line. It does not make
// the editor multi-line: set Editor.SingleLine yourself.
Lines int
// Role is the field's role: RoleTextbox by default; a combobox's
// field is RoleCombobox.
Role Role
}
EditorField is how an editor field looks: the placeholder shown while empty, an optional leading icon, and a minimum height in lines.
type Flex ¶
type Flex struct {
Axis layout.Axis // layout.Horizontal (the zero value) or Vertical
Gap unit.Dp // between children
Align layout.Alignment // cross axis; see the type doc
Justify layout.Spacing // main axis; see the type doc
Pad unit.Dp // all sides
PadX, PadY unit.Dp // override Pad on one axis when non-zero
Bg, Border color.NRGBA // drawn with th.Styled (theme stroke width)
Radius unit.Dp // the surface's corner radius
W, H unit.Dp // exact size; 0 leaves it to the constraints
MinW, MaxW unit.Dp // 0 is no limit
MinH, MaxH unit.Dp // 0 is no limit
FillW bool // take the full available width
FillH bool // take the full available height
}
Flex is the styled flex container: a row or column with gaps, padding, an optional surface and size limits, in one zero-value struct.
kit.Flex{Axis: layout.Vertical, Gap: kit.Space2, Pad: kit.Space4,
Bg: th.Panel, Border: th.Border, Radius: th.Radius,
}.Layout(gtx, th, kit.Rigid(title), kit.Flexed(1, body))
Spacing values (Gap, Pad*) are scaled by th's Density; sizes are not. Align is the cross axis (zero: Start), Justify the main axis (zero: SpaceEnd, packed at the start); Justify only matters when the container is wider than its children, so pair it with FillW/FillH or W/H.
type Focus ¶
type Focus struct {
// contains filtered or unexported fields
}
Focus makes an area keyboard-focusable: a Tab stop that can hold focus and receive actions. Anything can own one (a canvas, a terminal, a list). The zero value is ready to use. Focus is its own event tag, so it must not be copied or moved after its first Layout.
func (*Focus) Layout ¶
Layout lays out w as the focusable area and records it in the current KeyContext, so actions resolve from here when it is focused.
func (*Focus) RequestQuiet ¶
RequestQuiet gives f focus without a ring until the keyboard is used. Pointer clicks use it: like CSS :focus-visible, a click hides the ring even when f already had keyboard focus.
type FocusGroup ¶
type FocusGroup struct {
Active string // id of the active item
// contains filtered or unexported fields
}
FocusGroup makes a composite (list, tree, table, menu, toolbar) one Tab stop with an active item, which arrow keys move (WAI-ARIA "active descendant"). The group's container holds Gio focus, so the active item may be scrolled out of view and not laid out. The zero value is ready to use; like Focus, a FocusGroup must not be copied after its first Layout.
func (*FocusGroup) Focus ¶
func (g *FocusGroup) Focus(gtx layout.Context)
Focus gives the group keyboard focus.
func (*FocusGroup) FocusHandle ¶
func (g *FocusGroup) FocusHandle() *Focus
FocusHandle is the group's focus: a popup focuses it on open (Popup.FocusOnOpen), and keys the group leaves unclaimed are read with it as the key.Filter's Focus.
func (*FocusGroup) FocusQuiet ¶
func (g *FocusGroup) FocusQuiet(gtx layout.Context)
FocusQuiet gives the group focus without a ring until the keyboard is used.
func (*FocusGroup) HasFocus ¶
func (g *FocusGroup) HasFocus(gtx layout.Context) bool
HasFocus reports focus on the group, ring or not.
func (*FocusGroup) Join ¶
func (g *FocusGroup) Join(c *Clickable, active bool)
Join makes c a member of the group for this frame: no Tab stop of its own, clicks focus the group. When active is true, c is the active item and draws the focus ring while the group is focused. Call it in the handle pass, before c.Clicked.
func (*FocusGroup) Layout ¶
func (g *FocusGroup) Layout(gtx layout.Context, id string, w layout.Widget) layout.Dimensions
Layout lays out w as the group's single focusable area. Something must name that area with the same id, so tests and screen readers can name the group and report its active item: kit's lists do through List; a custom group calls Tag(gtx, id) at the top of w, which lands on the group's area.
func (*FocusGroup) RingVisible ¶
func (g *FocusGroup) RingVisible(gtx layout.Context) bool
RingVisible reports keyboard focus on the group with its ring shown (see Focus.RingVisible).
type FocusVisible ¶
type FocusVisible struct {
// contains filtered or unexported fields
}
FocusVisible decides whether a focused control draws its focus ring, as CSS :focus-visible does: focus given by a pointer hides the ring until the keyboard is used, and focus given by the keyboard shows it. The zero value shows the ring. Focus and Clickable use one; a custom focusable keeps one beside its tag.
func (*FocusVisible) Hide ¶
func (v *FocusVisible) Hide()
Hide hides the ring until Show, or until the control loses focus. Call it when a pointer gives the control focus.
func (*FocusVisible) Show ¶
func (v *FocusVisible) Show()
Show shows the ring again. Call it when the keyboard acts on the control or gives it focus.
func (*FocusVisible) Visible ¶
func (v *FocusVisible) Visible(focused bool) bool
Visible reports whether to draw the ring, given whether the control holds focus. Losing focus resets the state, so the next focus starts visible.
type Fonts ¶
type Fonts struct {
Name string // recorded in Theme.Fonts and theme tokens
UI, Mono font.Typeface // faces for UI text and for code and logs
Faces []font.FontFace // the font files; UseFonts does not modify them
}
Fonts is a set of bundled typefaces: a UI face and a code face, with the font files to shape them. See package kit/fonts for the curated sets.
type FrameStats ¶
type FrameStats struct {
// Build is the time spent in the frame function, on the UI goroutine.
Build time.Duration
// Submit is the time handing the frame to the window took (encoding
// and submitting it to the GPU, where the platform renders inline).
Submit time.Duration
// Render is the renderer's time encoding and submitting the frame to
// the GPU, on the CPU. No backend reports the GPU's own time.
Render time.Duration
// PathBuilds is the running count of shapes the GPU flattened and
// uploaded; subtract an earlier reading for the shapes built since.
// Shapes rebuilt every frame are drawing that defeats the caches
// (see kit.DrawCache).
PathBuilds uint64
// Layer counters are running totals from the renderer (see gpu.Stats).
LayerCaptures, LayerEffects uint64
LayerFallbacks, LayerEffectFallbacks, LayerTargetAllocations uint64
// Animating reports whether the frame asked for the next one straight
// away. Only then is the gap to the next frame its pace: a frame drawn
// for input or a timer follows a wait, not a slow frame.
Animating bool
}
FrameStats describes the last frame App drew, for performance overlays.
type HoverArea ¶
type HoverArea struct {
// contains filtered or unexported fields
}
HoverArea tracks whether the pointer is over an area, including its children: for a region that reacts to hover without being pressable (a table row, a card). Controls get hover from Theme.Press's State instead. The zero value is ready to use; it must not be copied after first use.
type Icon ¶
Icon draws a vector glyph in a size×size square and returns that size. Prefer icons over symbol characters: the bundled fonts cover Latin text, not ✓ ↻ ▾ ▸ (tofu boxes). The Icon* functions are the built-in set; any function of this shape is an icon.
type Image ¶
type Image struct {
// contains filtered or unexported fields
}
Image holds an uploaded image operation across frames, so the image is uploaded once rather than on every layout. Decode off the UI goroutine; call Set on it, on the UI goroutine, when the decoded content changes. The zero value holds no image. An Image holds no event tags: a copy refers to the same uploaded image until either copy is Set again.
type Keymap ¶
type Keymap struct {
// contains filtered or unexported fields
}
Keymap binds key chords to functions. Bind once, Attach it every frame where it applies, and list Bindings to build menus, a help screen or a command palette. The zero value is an empty keymap.
v.keys.MustBind("Shortcut+1", "Go to Overview", func() { v.page = "overview" }) // once
func (v *view) Frame(gtx layout.Context) {
v.keys.Attach(gtx)
v.handle(gtx)
v.layout(gtx)
}
Attached at the top level a keymap is window-wide; attached inside a KeyContext it applies only while focus is within that context, and wins over keymaps further out. Keys bubble like DOM events: the focused widget reads its keys while it is laid out, so it gets first pick (a focused text field keeps Ctrl+A); keys nobody claimed reach the keymaps after layout. While a text field (Theme.EditorField) has focus, chords that type text ("1", "?", "Shift+A") are left to it, so single-key shortcuts never eat typing.
Chords: modifiers joined with "+", then a key: "Ctrl+K", "Shift+Ctrl+P", "Alt+Up", "F1", "Escape", "Back" (Android), "Shortcut+S", "Ctrl++". Shortcut is Cmd on macOS and Ctrl elsewhere. A key written as a physical key code ("KeyQ", "Shift+Digit1"; see key.Code) binds the key in that place whatever the keyboard layout types with it: bind by place for keys chosen for where they sit (a game's WASD), by name for keys chosen for what they say.
A Keymap belongs to the UI goroutine, and its bound functions run there.
func (*Keymap) Attach ¶
Attach makes k's bindings live for this frame in the current KeyContext (window-wide at the top level). Call it anywhere in the frame: keys are resolved after layout, from the focused widget outward.
Without a kit.Window (plain Gio) there is no dispatch tree, so Attach reads the unclaimed keys itself, at the point it is called: call it last in the frame.
func (*Keymap) Bind ¶
Bind binds the chord that spec writes (see Keymap) to run, under title. Rebinding a chord replaces its binding. It fails if spec does not parse.
func (*Keymap) BindActions ¶
BindActions binds the actions registered in a to chords: defaults maps action ids to chords, and overrides, a JSON object of the same shape (the user's preferences; nil for none), takes precedence. An empty chord in either leaves an action unbound.
BindActions can be called again when the overrides change: it first removes every binding it made earlier for a's actions, so a shortcut the user cleared stops working. Bindings made with Bind are kept unless an action takes their chord.
A binding runs its action only while the action is enabled. While it is disabled, the binding does not take its chord: the key bubbles on to outer keymaps and action handlers, as if unbound.
Invalid JSON, invalid chords and two actions sharing a chord are errors and change nothing, so a bad preference file cannot silently change shortcuts. Override ids that name no action are skipped: the rest is bound and an *UnknownActionsError is returned, which callers should log rather than treat as fatal.
func (*Keymap) Bindings ¶
Bindings lists every binding in the order bound. It returns a copy: changing it does not change k.
func (*Keymap) Hint ¶
Hint returns the display chord of the binding with this title ("" if none). Titles are display strings, which may be translated or repeated; for bindings made by BindActions prefer HintFor.
type List ¶
type List struct {
widget.List
// Role is the role of the list's area, which carries its id
// (RoleListbox, RoleTree, RoleGrid); 0 for none.
Role Role
// contains filtered or unexported fields
}
List is the state of a th.List: Gio's widget.List plus smooth wheel scrolling, a gliding thumb and the continuity check behind Jumps. The zero value is ready to use. Like Gio's own widget state, a List identifies its input areas by address: do not copy it after first use.
The embedded widget.List is a supported escape hatch. Reading or setting its Position between frames (to save and restore a scroll offset or jump to an item) works as in Gio, and th.List picks the change up on the next frame. Laying the embedded list out directly bypasses kit: no wheel smoothing, scrollbar or continuity check.
func (*List) Jumps ¶
Jumps counts frames where the content moved a different distance than the scroll asked for (a visible skip). Tests assert it stays 0; with GIOKIT_TRACE=1 each one is logged to stderr.
func (*List) ScrollIntoView ¶
ScrollIntoView scrolls the least distance that shows item i whole, using last frame's layout (rows of similar height). Call it from a handler; the next frame shows the result. A negative i scrolls to the top; an i past the end scrolls to the end when the list is next laid out.
type MenuRow ¶
type MenuRow struct {
Icon Icon // optional, before the label
Label string // also the spoken name
Hint string // shortcut or detail, dim, at the end
Danger bool // destructive: drawn in the bad colour
Checked bool // a check mark: the selected option
Highlighted bool // lit without focus: a combobox's keyboard choice
// Content, if set, is drawn instead of the label text (Label is still
// spoken). It may run more than once per frame: MenuRowWidth measures it
// with input disabled and its operations discarded. It must only draw:
// state it changes stays changed, so it must not read events or count
// its calls.
Content layout.Widget
Role Role // RoleMenuItem by default; RoleOption in selects and pickers
}
MenuRow is one row of a menu-like list: menu items, select options, combobox suggestions, command palette results.
type Metrics ¶
type Metrics struct {
IconSize unit.Dp // icons in controls, rows and fields
IconSizeLg unit.Dp // icons in alerts and toasts
CheckSize unit.Dp // checkbox box
IconButtonSize unit.Dp // square icon-only button
SwitchWidth unit.Dp // switch track width
SwitchHeight unit.Dp // switch track height, and a slider's height
HitSize unit.Dp // smallest pointer target for thin things (split handles, scrollbars)
PaneMinSize unit.Dp // smallest split pane
MenuMinWidth unit.Dp // menus are at least this wide
ListMaxHeight unit.Dp // a select's list scrolls past this
PopoverMaxWidth unit.Dp // popover panels are at most this wide
DialogMaxWidth unit.Dp // modal dialogs are at most this wide
ToastWidth unit.Dp // a toast's width, narrowed in small windows
ReadingWidth unit.Dp // longest comfortable text block (empty states)
LabelWidth unit.Dp // form label column
NarrowWidth unit.Dp // below this, forms stack labels above fields
}
Metrics are the theme's fixed sizes: everything that is neither spacing (the SpaceN scale, through Theme.Space) nor a corner (Theme.Radius). Components read them from the theme instead of writing numbers.
func DefaultMetrics ¶
func DefaultMetrics() Metrics
DefaultMetrics returns giokit's sizes at density 1. Each call returns a fresh value.
type OKLCH ¶
type OKLCH struct {
L float64 // perceived lightness, 0 (black) to 1 (white)
C float64 // chroma, 0 for grey; sRGB colours stay below about 0.37
H float64 // hue angle in degrees, 0 to 360
}
OKLCH is a perceptual color: L lightness 0..1, C chroma (~0..0.37), H hue in degrees. Equal steps in L look like equal steps in brightness, which is what makes generated palettes consistent across hues.
It is the polar form of Björn Ottosson's Oklab color space ("A perceptual color space for image processing", 2020, https://bottosson.github.io/posts/oklab/); the conversion matrices below are the ones published there.
type Palette ¶
type Palette struct {
Bg color.NRGBA // window background
Panel color.NRGBA // bars, sidebars, cards
Surface color.NRGBA // buttons, inputs, selected nav item
Hover color.NRGBA // hovered rows, nav items and headers; differs from Bg and Panel, so it shows on cards
Border color.NRGBA // panel separators, button and input outlines
Divider color.NRGBA // row separators, card outlines
Fg color.NRGBA // primary text
Muted color.NRGBA // secondary text
Dim color.NRGBA // tertiary text, headings, disabled
Accent, AccentBg, AccentBorder color.NRGBA // primary actions, selection, "open" state
OnAccent color.NRGBA // text/icons on a solid Accent fill
Good, GoodBg color.NRGBA // done / success
Warn, WarnBg color.NRGBA // needs attention
Bad, BadBg color.NRGBA // errors, destructive actions
Focus color.NRGBA // keyboard focus ring
Overlay color.NRGBA // tooltips, popovers, menus, dialogs (drawn above content)
Scrim color.NRGBA // translucent wash behind a modal dialog
}
Palette holds the semantic color tokens every component draws from. Each names a role, not a hue, so one set of components reads correctly in any palette; the comments say where each role appears. Legible fixes a palette's text colors to meet their contrast targets.
func GeneratePalette ¶
GeneratePalette derives every token from a seed in OKLCH: neutrals on a fixed lightness ladder tinted by Neutral's hue, accent and status colors at lightnesses that keep text readable on the background in both modes. Apply it to an existing theme with Derive to keep its fonts and metrics.
func (Palette) Legible ¶
Legible returns p with every text color moved in lightness, away from the backgrounds and only as far as needed, until it meets its contrast target on every surface it is drawn on: Fg, Muted and Dim on Bg, Panel, Surface, Hover and Overlay, and on the pressed tints of Surface and Overlay; Accent and the status colors there and on their own tinted backgrounds; OnAccent on Accent. Colors that already pass are unchanged, and hue and chroma are kept. Focus follows Accent.
dark says which way text moves: lighter for a dark palette, darker for a light one (OnAccent the opposite way). It is the caller's statement of the palette's mode, normally Theme.Dark, and is not derived from Bg, so a deliberately unusual palette keeps its intent.
func (Palette) WithContrast ¶
WithContrast raises a palette's contrast for any theme, generated or hand-made: level 0 returns p unchanged, 1 is high contrast (text toward AAA, borders and the focus ring at least 3:1 against the background, as WCAG asks of non-text UI). Levels above 1 count as 1. dark is as for Legible.
type Pool ¶
type Pool[T any] struct { // contains filtered or unexported fields }
Pool keeps per-item widget state keyed by a stable id (never a list index). The zero value is an empty pool. Values are allocated by the pool and keep their address while they live, so they may be event tags (Clickable); the pool itself must not be copied after first use.
Entries live until Delete, or until Sweep finds them untouched. Components whose data can grow without bound (logs, file trees, chat) call Sweep once per frame after calling Get for every live id; ids that left the data are then dropped after 65 to 128 Sweeps untouched instead of leaking. Like all kit state, a Pool belongs to the UI goroutine.
func (*Pool[T]) Each ¶
Each calls f for every id with state, in no particular order. f may Delete entries (the current one or others; deleted ones not yet visited are skipped), but must not call Get for new ids: whether Each visits them is unspecified.
type Popup ¶
type Popup struct {
// MatchWidth makes the panel at least as wide as its anchor (selects).
MatchWidth bool
// KeepFocus leaves keyboard focus where it is when the panel opens (a
// combobox keeps typing in its field).
KeepFocus bool
// Role is the panel's role (RoleMenu, RoleListbox, RoleDialog); 0 for
// none.
Role Role
// contains filtered or unexported fields
}
Popup is the state of a floating panel laid out by Theme.Popover (and the menus, selects and pickers built on it). The zero value is closed.
A Popup identifies its anchor and panel areas to Gio by the addresses of its fields, like Gio's own widget state: do not copy one after first use.
func (*Popup) DidDismiss ¶
DidDismiss reports whether the user closed the panel (Escape, or a press outside it) since the last call, and whether it was by keyboard: return focus to the trigger then, with a ring if by keyboard.
func (*Popup) FocusOnOpen ¶
FocusOnOpen makes the popup focus f when it opens, instead of its panel (a menu focuses its item group). Set it before laying out the Popover.
func (*Popup) Opening ¶
Opening reports that the popup opened since its last layout, which moves focus into it: a component picks what to focus (a calendar's day), or keeps a just-opened list from closing.
func (*Popup) PanelFocus ¶
PanelFocus is the panel's own focus, for reading keys (Tab) while the panel holds it.
type Role ¶
Role is what a control is, in the WAI-ARIA vocabulary: richer than upstream Gio's five semantic classes, so a tree node, a table row and a menu item are told apart. It is the fork's semantic.ClassOp: add it to the control's clip area (role.Add(gtx.Ops)) beside its Tag, and it is part of the semantic tree that kittest (h.Role, h.ByRole) and the platform read. The zero value, semantic.Unknown, is no role.
type Seed ¶
type Seed struct {
Name string // the generated theme's Name
Accent color.NRGBA // brand / primary color
Neutral color.NRGBA // tints the grays; its hue matters, chroma is capped (zero value = pure gray)
Dark bool // generate a dark palette
// Contrast 0 (default) … 1 (high contrast: brighter text, stronger borders).
Contrast float64
}
Seed is the input to Generate: a couple of brand colors in, a full contrast-checked theme out.
func PresetSeeds ¶
func PresetSeeds() []Seed
PresetSeeds returns the seeds of the generated presets, in display order. Each call returns a fresh slice.
type State ¶
type State struct {
Hovered, Pressed bool // the pointer is over the area; a press is held on it
// Focused reports focus with a visible ring: draw one. Focus a click
// gave (FocusOnClick, a FocusGroup) leaves it false until the keyboard
// is used.
Focused bool
Hover float32 // Hovered, animated 0..1: lerp tints with it
}
State is the live interaction state handed to a component's draw callback. It is all false inside Theme.Disable (which also dims the drawing).
type Strings ¶
type Strings struct {
Expand, Collapse string // tree toggles: "Expand %s"
SortedAsc string // a sorted column header's spoken name: "%s (asc)"
SortedDesc string // the same, sorted descending: "%s (desc)"
Increase, Decrease string // stepper buttons: "Increase %s"
MoveUp, MoveDown string // reorder buttons: "Move %s up"
Reorder string // a reorder drag handle: "Reorder %s; ..."
Required string // validation
EnterNumber string // a number field's text does not parse
NumberRange string // "Use %g to %g"
Commands string // the command palette title
CommandPlaceholder string // the command palette's query hint
NoCommands string // the command palette found nothing
NoLogLines string // log view: the buffer is empty
NoLogMatches string // log view: the filters hide every line
Latest string // log view: jump to the newest line
Accordion string // spoken names of groups
Breadcrumbs string // the Breadcrumbs group
Toolbar string // the Toolbar group
Form string // the Form group
PrevPage, NextPage string // calendar paging buttons
Close string // close buttons
Dismiss string // a toast's dismiss button
DateFormat string // a date field's text, as a Go time layout
MonthFormat string // a calendar's month title, as a Go time layout
DecadeFormat string // a calendar's decade title: "%d–%d", first and last year
Months [12]string // short month names, January first: a calendar's month grid
Weekdays [7]string // short weekday names, Sunday first: a calendar's column heads
Video string // a video's spoken name when the app gives none
}
Strings is the text kit itself shows or speaks. Fields with %s, %g or %d verbs are fmt formats (%[1]s reorders for languages that need it), and Validate checks that a translation keeps their verbs; DateFormat and MonthFormat are Go time layouts. Replace the theme's Strings to translate, starting from English.
func English ¶
func English() Strings
English returns the default Strings. Each call returns a fresh value: start a translation from it and replace the fields that differ.
func (Strings) Validate ¶
Validate checks the fmt formats of a translation, which go vet cannot: each format field must use every argument kit passes it, with the same verb as English (%s for names, %g for numbers, %d for years), and no others. Arguments may be reordered with explicit indexes ("%[2]g … %[1]g"). It returns an error naming the first field that does not. Time layouts (DateFormat, MonthFormat) are not checked.
type Surface ¶
type Surface struct {
Bg, Border color.NRGBA // fill and outline; a zero colour draws nothing
Radius unit.Dp // clamped to half the shorter side: huge values make pills
Focus color.NRGBA // when set, a focus ring in this colour replaces Border
Stroke unit.Dp // border width; 0 is a 1dp hairline (New's Theme.Stroke)
Ring unit.Dp // focus ring width; 0 is 2dp (New's Theme.Ring)
}
Surface draws a (rounded, optionally outlined) background sized to its content. Focus replaces the border with a ring in that color (keyboard focus). Components build surfaces with Theme.Styled, which fills Stroke and Ring.
type Table ¶
type Table struct {
Cols []Column // left to right; header and rows use the same widths
Inset unit.Dp // horizontal padding inside each row
RowPad unit.Dp // vertical padding inside each row
}
Table lays out a header and rows over the same columns, so they always line up. It is the layout primitive: it draws, but holds no selection, sorting or keyboard navigation. For an interactive data grid use ui.DataTable, which is built on it.
func (Table) Cells ¶
func (tb Table) Cells(gtx layout.Context, cell func(gtx layout.Context, col int) layout.Dimensions) layout.Dimensions
Cells lays out one line of cells across the columns; cell draws column col's content.
func (Table) Row ¶
func (tb Table) Row(gtx layout.Context, th *Theme, h *HoverArea, id string, last bool, cell func(gtx layout.Context, col int, hovered bool) layout.Dimensions) layout.Dimensions
Row draws one hoverable row with id, followed by a divider unless last is set (the final row). cell gets the row's hover state so controls can light up with the row.
type Task ¶
type Task struct {
// contains filtered or unexported fields
}
Task is a running Spawn. Cancel it when its result is no longer wanted: a view closed, or a newer query replaced it (type-ahead):
v.search.Cancel()
v.search = kit.Spawn(app, func(ctx context.Context) ([]Hit, error) { return find(ctx, q) },
func(hits []Hit, err error) { v.hits = hits })
Tasks come from Spawn. The zero Task is not running and has no work to cancel; Cancel on it does nothing. The UI goroutine owns a Task, like all state: Cancel and Running are not safe from the work function.
func Spawn ¶
Spawn runs work off the UI goroutine and delivers its result to done on the UI goroutine (GPUI: cx.spawn), unless the returned Task was cancelled first. With a nil App (tests), work runs inline and the Task is finished.
type TextSpan ¶
type TextSpan struct {
Text string // the run's text; spans join without separators
Size unit.Sp // 0 is the theme's body size
Strong, Muted bool // semibold weight; Muted instead of Fg colour
}
TextSpan is a themed run in one wrapping paragraph. The zero-valued size uses body text; Strong and Muted select theme roles rather than raw colors.
type Theme ¶
type Theme struct {
Palette // the colour tokens
Name string // the theme's display name ("Dark", a preset's name)
Dark bool // the palette is dark (for apps choosing images/icons)
Type TypeScale // text sizes; scale them all with Type.Scaled
// Radius is the corner radius of controls (buttons, fields, selects).
// Everything else derives from it: RadiusSm (checkboxes, menu rows, tabs),
// RadiusLg (cards, menus, dialogs) and RadiusFull (badges). 0 is square
// everywhere; a huge value makes pill-shaped controls.
Radius unit.Dp
// Stroke is the border width of controls, fields and cards (1 is a
// hairline). Ring is the keyboard focus ring width (2; thicker is
// easier to see). Styled applies both to a Surface that leaves its own
// widths 0.
Stroke, Ring unit.Dp
// Density multiplies spacing (Space): 0.8 compact, 1 regular, 1.2
// comfortable. 0 means 1, so a theme built without it is regular.
Density float32
// Controls is the height class of buttons, fields, selects, tabs and menu
// rows; they line up with each other at every size.
Controls ControlSize
// Elevation scales the shadow under menus, popovers and dialogs:
// 0 flat (border only), 1 soft, 2 strong.
Elevation float32
// HeadingWeight is the weight of page headings.
HeadingWeight font.Weight
// Motion scales every animation duration (Dur). Unlike Density, 0 is
// meaningful: it disables animation (reduced motion), and continuous
// animations (spinners) then draw a static frame.
Motion float32
// DisabledAlpha is the opacity of controls inside Theme.Disable.
DisabledAlpha float32
Metrics // fixed sizes: icons, controls, overlay widths
Strings Strings // text kit shows or speaks (English by default)
UI, Mono font.Typeface // bundled typefaces for UI text and code/logs
Fonts string // name of the font set (UseFonts); "Go" by default
// Shaper shapes all text, from bundled fonts only. UseFonts replaces it.
Shaper *text.Shaper
}
Theme is everything a component reads to draw: colors, text sizes and faces, spacing, shape, motion and the strings it shows or speaks.
Build a theme with New, Dark, Light, Generate or ThemeFromTokens; the zero Theme has no shaper and cannot draw text. Fields may be written directly, between frames, and take effect from the next frame. A theme belongs to the UI goroutine. Copies made by Derive (or by assignment) share its Shaper, which is not safe for concurrent use, so a copy is not permission to draw on another goroutine.
func CatppuccinFrappe ¶
func CatppuccinFrappe() *Theme
CatppuccinFrappe is Catppuccin's lightest dark flavor, with its lavender accent.
func CatppuccinLatte ¶
func CatppuccinLatte() *Theme
CatppuccinLatte is Catppuccin's light flavor, with its lavender accent.
func CatppuccinMacchiato ¶
func CatppuccinMacchiato() *Theme
CatppuccinMacchiato is Catppuccin's middle dark flavor, with its lavender accent.
func CatppuccinMocha ¶
func CatppuccinMocha() *Theme
CatppuccinMocha is Catppuccin's darkest flavor, with its lavender accent.
func New ¶
New builds a theme from a palette, with giokit's default type scale, metrics, shape, motion and English strings, and the bundled Go fonts. It uses p as given; Palette.Legible fixes text contrast first if needed.
New creates a text shaper, which loads fonts and caches shaped text: it is too costly to call per frame. Build themes once and restyle with Derive, which shares the shaper.
func Presets ¶
func Presets() []*Theme
Presets returns the bundled themes in display order (Dark first, then the seeded ones, then Black, the Catppuccin flavors and Pink). They share one font shaper, so switching between them keeps text caches warm.
func ThemeFromTokens ¶
ThemeFromTokens builds a theme from a W3C Design Tokens (DTCG) JSON file, the exchange format of Figma Variables (via Tokens Studio), Penpot and Style Dictionary. It starts from base (nil means Dark()), so a file only needs the tokens it changes; base itself is not modified.
It reads these token paths:
color.<token> bg, panel, surface, hover, border, divider, fg, muted, dim,
accent, accent-bg, accent-border, on-accent, good, good-bg,
warn, warn-bg, bad, bad-bg, focus, overlay, scrim
font-size.<step> caption, small, body, text, stat, title
size.<metric> icon, icon-lg, check, icon-button, switch-width,
switch-height, hit, pane-min, menu-min-width,
list-max-height, popover-max-width, dialog-max-width,
toast-width, reading-width, label-width, narrow-width
radius, stroke, ring non-negative dimensions
elevation, density, motion non-negative numbers
disabled-opacity number from 0 to 1
heading-weight DTCG font weight, 1 to 1000
controls "small", "medium" or "large"
dark boolean
name, fonts strings
plus the file's top-level "$name", used when no name token changes the name. Every other path is ignored, even when it holds a broken alias, so a full design-system file with reference ramps works as-is. The font set is recorded by name only: apply it with th.UseFonts(fonts.ByName(th.Fonts)).
Values may be aliases ("{color.blue.500}") to any token in the file. Colors are hex strings ("#rgb", "#rrggbb", "#rrggbbaa") or DTCG color objects in the srgb color space: {"colorSpace":"srgb","components":[r,g,b], "alpha":a} with r, g, b and a from 0 to 1, or {"hex":"#rrggbb","alpha":a}. Dimensions are numbers, strings ("6px", "1.5rem") or DTCG objects ({"value":6,"unit":"px"}); px, dp and sp are all one giokit unit, and a rem is 16 of them.
A malformed value at a path it reads, including an alias that does not resolve, is an error. Every such problem is reported as a *TokenError naming its path, joined with errors.Join, and no theme is returned.
func (*Theme) AnchoredList ¶
func (t *Theme) AnchoredList(gtx layout.Context, a *AnchoredList, id string, ids []string, item layout.ListElement) layout.Dimensions
AnchoredList lays out a.List with one item per id: item(gtx, i) draws ids[i]. ids is read only during the call and may be changed freely between frames. If the item first visible last frame has moved to another index, the list scrolls with it, keeping its offset. Checking costs O(1) per frame while that item stays put; finding it after it moves is O(n).
func (*Theme) Caption ¶
Caption is the small uppercase label used for section and column headings. It uppercases s with strings.ToUpper, Unicode's language-independent mapping: for a language with its own casing rules (Turkish dotted i), pass s already uppercased.
func (*Theme) CodeBlock ¶
func (t *Theme) CodeBlock(gtx layout.Context, s string, size unit.Sp, c color.NRGBA) layout.Dimensions
CodeBlock is Code that wraps: monospace paragraphs (previews, output).
func (*Theme) ControlPad ¶
ControlPad scales a control's inner padding v by density and size (ControlDefault: the theme's Controls), so buttons, fields and selects of one size share a height.
func (*Theme) Derive ¶
Derive returns a copy of t changed by f; t is unchanged. Use it to restyle a subtree (a danger zone, a sidebar with its own tint, a compact table) without touching components:
danger := th.Derive(func(t *kit.Theme) { t.Accent, t.AccentBg = t.Bad, t.BadBg })
Value fields (colors, sizes, Strings, Metrics) are the copy's own. The Shaper is shared, which keeps text caches warm; calling UseFonts on the copy gives it a new shaper without touching t.
func (*Theme) Disable ¶
Disable lays out w disabled when disabled is true, and normally otherwise. Nothing inside gets input (clicks, hover, keys, wheel, drags), it leaves the Tab order, the semantics say disabled (screen readers, kittest), and it draws at the theme's DisabledAlpha. Wrap one control or a whole section:
th.Disable(gtx, !v.dirty, func(gtx layout.Context) layout.Dimensions { return ui.Button{ID: "save", Text: "Save"}.Layout(gtx, th, &v.save) })
func (*Theme) EditorField ¶
func (t *Theme) EditorField(gtx layout.Context, e *widget.Editor, id string, f EditorField) layout.Dimensions
EditorField lays out e as a field: theme chrome, a ring while focused, and the whole field (padding included) as the click target that focuses the editor. ui.TextField, ui.TextArea and every editor-based component are built on it.
func (*Theme) Field ¶
Field draws field chrome around w: full width, the control padding for the theme's control size, surface and border, a hover tint from st.Hover, and the focus ring while st.Focused. Field-like triggers (select, date) are built on it; TextField draws the same chrome.
func (*Theme) FieldPad ¶
func (t *Theme) FieldPad(size ControlSize) unit.Dp
FieldPad is the vertical padding of a field, or of a field-like control (a select's trigger, a button, a navigation row), at size: fieldPadY scaled by density and size as ControlPad does. Controls of one size that use it share a height.
func (*Theme) FloatingPanel ¶
FloatingPanel is the floating surface of menus, popovers, dialogs and toasts: overlay fill, hairline border, a shadow scaled by Elevation.
func (*Theme) FocusRing ¶
FocusRing draws the theme's focus ring just inside a rounded rect of size sz with corner radius r in pixels.
func (*Theme) Highlight ¶
Highlight is the background of a row or cell lit by lit, from 0 (none) to 1: hover animates it, focus, press or a keyboard choice light it fully. Values outside 0..1 are clamped. Menu rows, calendar cells and list rows use it.
func (*Theme) List ¶
func (t *Theme) List(gtx layout.Context, l *List, id string, n int, item layout.ListElement) layout.Dimensions
List is a vertical scrolling list with a thin overlay scrollbar (it never steals width, so rows stay aligned with headers). id names the scroll region; the scrollbar is <id>/scrollbar (thumb <id>/thumb).
Unlike material.List it applies scrollbar drags before laying out the list, so the frame that handles a drag also shows it.
func (*Theme) MenuRow ¶
MenuRow lays out r as a pressable row (lit on hover, focus or Highlighted) filling the width. Ids and clicks are c's, as for a button.
func (*Theme) MenuRowWidth ¶
MenuRowWidth is the width in pixels r needs, to size a popup to its widest row. It measures r.Content, if set, by running it (see MenuRow.Content).
func (*Theme) MissingGlyphs ¶
MissingGlyphs returns the runes in s that the theme's fonts can't draw (they would render as tofu boxes), each once, in order of first appearance. Whitespace and control runes are ignored.
It shapes each rune on its own, so it judges runes, not text: a glyph that only exists in context (a ligature, a combining mark drawn with its base) is not checked. It reads the font glyph index from the low 32 bits of Gio's text.GlyphID, where 0 is .notdef; that layout is Gio's internal encoding, and a Gio upgrade could change it.
func (*Theme) Modal ¶
func (t *Theme) Modal(gtx layout.Context, d *Dialog, id string, page layout.Widget, dialog layout.Widget) layout.Dimensions
Modal lays out page, and while d is open a dialog above it. The page is laid out disabled meanwhile, without dimming it twice (the scrim does): nothing behind the dialog takes input or focus, so Tab cycles inside the dialog for free. Call it near the root, around everything the dialog should cover. Escape or a click on the backdrop closes the dialog unless it is Persistent. Unlike a Popup, a dialog closes on a full click (press and release) on the backdrop, so a drag that starts in the dialog and ends outside it does not close it.
func (*Theme) ParagraphLine ¶
func (t *Theme) ParagraphLine(gtx layout.Context, s string, c color.NRGBA, w font.Weight) layout.Dimensions
ParagraphLine is Paragraph with a font weight: it wraps too. It suits a block of text whose emphasis changes with state, such as the current line of lyrics.
func (*Theme) Popover ¶
func (t *Theme) Popover(gtx layout.Context, p *Popup, id string, anchor layout.Widget, content layout.Widget) layout.Dimensions
Popover lays out anchor, and while p is open a floating panel holding content below it. Open it from your handle pass (p.Show, or Toggle on a trigger's click); Escape or a press outside closes it. Popover is the primitive the other floating components (menus, selects, context menus) build on.
The panel is drawn in a deferred layer, so it lands above everything, positioned against its anchor's window position in the last frame (input.Source.Bounds). It opens below its anchor and flips above it, or shifts sideways, to stay inside the window.
While the panel is open, a backdrop covers the window: a press outside the panel closes it and goes nowhere else. The backdrop's id is "<id>/backdrop"; kittest's audit treats widgets under a backdrop as intentionally unreachable, not occluded.
Anchor and panel share one KeyContext nested in the opener's, so Escape reaches the innermost open popup first (also with focus on its trigger or, for KeepFocus, its field), and anything it does not handle bubbles on.
func (*Theme) Press ¶
func (t *Theme) Press(gtx layout.Context, c *Clickable, id string, w func(gtx layout.Context, st State) layout.Dimensions) layout.Dimensions
Press makes w a pressable target with id: c's clicks, hover and focus, with hover animated at the theme's motion speed (none at Motion 0). w draws from the State, which is current for this frame; never read c.Hovered() earlier. Every kit button, row and cell is built on it; so can yours (add a semantic role and label inside w).
func (*Theme) Progress ¶
Progress is a thin full-width bar. value in 0..1; a negative value draws an indeterminate bar (a sliding segment; static when Motion is 0).
func (*Theme) RadiusFull ¶
RadiusFull is the corner of badges and pills: fully round, unless the theme is square (Radius 0).
func (*Theme) RadiusLg ¶
RadiusLg is the corner of containers: cards, menus, popovers, dialogs. It is 1.4 times Radius, at most 16dp, so pill-shaped controls don't make capsule-shaped cards.
func (*Theme) RadiusSm ¶
RadiusSm is the corner of small parts: checkboxes, menu rows, tabs. It is two thirds of Radius, at most 8dp.
func (*Theme) Required ¶
func (t *Theme) Required(id, value string) Validation
Required reports value as missing when it is empty after trimming space, with the theme's localized message (Strings.Required). Callers combine it with their own domain rules.
func (*Theme) SizedField ¶
func (t *Theme) SizedField(gtx layout.Context, size ControlSize, st State, w layout.Widget) layout.Dimensions
SizedField is Field at a control size (ControlDefault: the theme's), for components with a per-instance Size.
func (*Theme) Spinner ¶
Spinner is a rotating arc for "working…" states, size×size. It schedules frames with Loop, so a UI showing it still settles in kittest.
func (*Theme) StateColor ¶
StateColor is a control's fill base as drawn in st: hover moves it half way to a press, a press all the way. Buttons and fields use it.
func (*Theme) StatusColors ¶
StatusColors are a status's foreground, background and icon (badges, banners, toasts). A value outside the defined statuses draws as StatusInfo.
func (*Theme) Styled ¶
Styled fills a Surface's border and ring widths from the theme's Stroke and Ring where the Surface leaves them 0. Components build their surfaces through it, so Stroke and Ring apply everywhere.
func (*Theme) StyledText ¶
StyledText renders a wrapping paragraph with mixed emphasis. Its area carries the whole text as one semantic label. It has no inline links: put a Link widget beside it.
func (*Theme) Text ¶
func (t *Theme) Text(gtx layout.Context, s string, size unit.Sp, c color.NRGBA, w font.Weight) layout.Dimensions
Text draws a single line of text in the UI typeface, truncated to the width available. Its area hugs the text.
func (*Theme) Tint ¶
Tint mixes c toward the foreground by amount, from 0 to 1 (PressTint is a full press): a hover/press colour that works on light and dark themes alike. A transparent c gives a translucent foreground. Values outside 0..1 are clamped.
func (*Theme) Tokens ¶
Tokens exports the theme as DTCG JSON, which ThemeFromTokens reads back to an equal theme, with one exception: the controls token writes both ControlDefault and ControlMedium as "medium", which reads back as ControlDefault, so ControlMedium comes back as ControlDefault (the same size). Keys are sorted, so files are stable and diff well.
It fails when a field holds a value ThemeFromTokens would reject: a non-finite or negative size or multiplier, a DisabledAlpha outside 0..1, an unknown ControlSize or a HeadingWeight outside DTCG's 1..1000. Each such field is reported as a *TokenError, joined with errors.Join.
type TokenError ¶
type TokenError struct {
Path string // token path, such as "color.bg", "radius" or "$name"
Err error // what is wrong with the value
}
TokenError reports a design token that ThemeFromTokens could not read or Theme.Tokens could not write.
func (*TokenError) Error ¶
func (e *TokenError) Error() string
Error formats the error as "kit: tokens: <path>: <cause>".
func (*TokenError) Unwrap ¶
func (e *TokenError) Unwrap() error
Unwrap returns the cause, for errors.Is and errors.As.
type Transition ¶
type Transition struct {
// contains filtered or unexported fields
}
Transition plays an entrance animation (fade + short slide) whenever key changes: use it for page or tab switches. Only the new page is drawn, so input never reaches a page that is leaving. The zero value is ready and shows its first page without animating. A Transition holds no event tags and may be copied.
type Tween ¶
type Tween struct {
// contains filtered or unexported fields
}
Tween animates a float toward a target. Animation in giokit is immediate-mode: call To every frame with the value you want, and it returns the value to draw this frame. There are no callbacks and nothing to start or stop.
x := s.slide.To(gtx, target, th.Dur(kit.DurNormal))
A moving tween requests an immediate redraw; kittest's Settle chases those on a virtual clock until it finishes (compare Loop).
The zero value snaps to the first target it sees (no animation on first appearance). A Tween holds no references and may be copied.
func (*Tween) From ¶
From restarts the animation from v toward the current target over d (to replay an entrance animation). It uses the easing of the most recent target change, or of the first To or ToEase call if the target has not changed since (EaseOut before any call).
func (*Tween) To ¶
To returns the value for this frame while moving toward target over d (EaseOut). Call it every frame, inside layout.
type TypeScale ¶
type TypeScale struct {
Caption unit.Sp // uppercase section labels, column headers
Small unit.Sp // secondary text: hints, captions under fields
Body unit.Sp // controls and most text
Text unit.Sp // reading text and empty-state titles
Stat unit.Sp // large figures (Stat cards)
Title unit.Sp // dialog and page titles
}
TypeScale is the theme's text sizes. Components read sizes from here, so a theme can be denser or roomier without touching components.
func DefaultType ¶
func DefaultType() TypeScale
DefaultType returns giokit's type scale, the Size* constants. Each call returns a fresh value.
type UnknownActionsError ¶
type UnknownActionsError struct {
IDs []string // the unknown ids, in the overrides' sorted order
}
UnknownActionsError lists override ids that name no registered action, typically a keymap written by a newer (or older) version of the app. BindActions returns it after binding everything else, so callers can log it and carry on.
func (*UnknownActionsError) Error ¶
func (e *UnknownActionsError) Error() string
Error lists the unknown ids.
type Validation ¶
type Validation struct {
FieldID string // the field's id
Message string // the error to show; empty means valid
}
Validation is the result of checking one field.
type Window ¶
type Window struct {
// contains filtered or unexported fields
}
Window holds the state that outlives a frame for one window: the key dispatch tree built during the last frame and what kittest needs to see of it. App.Run and kittest own one; a program driving Gio's loop itself calls Begin before its frame function and End after it.
gtx = w.Begin(gtx) frame(gtx) w.End(gtx)
The zero value is ready to use. A Window belongs to the goroutine that runs its window's frames; one Window serves one window.
func (*Window) Begin ¶
Begin starts a frame: it records the window's size and installs the dispatch tree in gtx, which KeyContext, OnAction and Focus use. It resets what the last frame recorded (focus groups, focus ids), so maps the window returned earlier are reused from here on. Every Begin needs a matching End on the same gtx.
func (*Window) End ¶
End resolves the key presses nothing claimed during the frame against the dispatch tree: from the node holding focus up to the window, the nearest attached keymap binding or action handler runs. Widgets that read keys themselves during layout (editors) asked first, so they keep theirs.
func (*Window) FocusedID ¶
FocusedID is the id of the control holding keyboard focus in the last frame (as recorded by FocusID), or "". src is the window's input source.
func (*Window) GroupActive ¶
GroupActive maps each focus group's id to its active member's id, when that member was laid out in the last frame. kittest reports it as the focused id, as a screen reader would. The map is borrowed, like GroupMembers'.
func (*Window) GroupMembers ¶
GroupMembers maps each focus group's id to its members' ids, in layout order, as laid out in the last frame. kittest uses it to count a group as one Tab stop. The map and its slices are borrowed: they belong to the window and are reused by the next frame's Begin, so copy what you keep.
Source Files
¶
- actions.go
- anchoredlist.go
- anim.go
- app.go
- clickable.go
- color.go
- dispatch.go
- doc.go
- draw.go
- drawcache.go
- feedback.go
- flex.go
- flow.go
- focus.go
- form.go
- glyphs.go
- hover.go
- icon.go
- id.go
- image.go
- inputs.go
- keymap.go
- menu.go
- metrics.go
- overlay.go
- pacing.go
- palette.go
- patterns.go
- pool.go
- root.go
- scroll.go
- scrolltrace.go
- semantic.go
- spacing.go
- strings.go
- styledtext.go
- table.go
- theme.go
- themes.go
- tint.go
- tokens.go
- trace.go
- widgets.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fonts holds giokit's curated font sets, bundled so text renders the same on every machine.
|
Package fonts holds giokit's curated font sets, bundled so text renders the same on every machine. |
|
Package forktrace adds Gio's low-level window events (wl_*, scroll_flush, gpu_frame, present) to GIOKIT_TRACE output, in order with kit's own lines, through the fork's app.GiokitTrace hook.
|
Package forktrace adds Gio's low-level window events (wl_*, scroll_flush, gpu_frame, present) to GIOKIT_TRACE output, in order with kit's own lines, through the fork's app.GiokitTrace hook. |
|
Package pad reads game controllers on every platform giokit runs on and turns them into per-frame button events.
|
Package pad reads game controllers on every platform giokit runs on and turns them into per-frame button events. |
|
Package store keeps an app's persistent data: small named entries, such as settings, a saved game or a sync token, each read and replaced whole.
|
Package store keeps an app's persistent data: small named entries, such as settings, a saved game or a sync token, each read and replaced whole. |
|
Package ui holds giokit's components, built only from package kit's exported API: anything here could be written outside giokit.
|
Package ui holds giokit's components, built only from package kit's exported API: anything here could be written outside giokit. |
|
Package x holds specialised widgets built on kit and kit/ui: a log view and a lyrics view.
|
Package x holds specialised widgets built on kit and kit/ui: a log view and a lyrics view. |
|
video
Package video draws streaming images (video, camera, remote screens) with Video, from a paint.Stream (in giokit's Gio fork).
|
Package video draws streaming images (video, camera, remote screens) with Video, from a paint.Stream (in giokit's Gio fork). |