GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - yogaui/yoga: A from-scratch, cross-platform UI framework in Go, drawn with WebGPU on desktop and in the browser.

BranchesTags
Open more actions menu

Latest commit

 

History

266 Commits
266 Commits

Folders and files

NameName
Last commit message
Last commit date
.cursor/skills/yoga-ui
.cursor/skills/yoga-ui
 
 
.github/workflows
.github/workflows
 
 
cmd
cmd
 
 
docs/assets
docs/assets
 
 
example
example
 
 
icons
icons
 
 
input
input
 
 
internal/pack
internal/pack
 
 
layout
layout
 
 
render
render
 
 
shape
shape
 
 
syntax
syntax
 
 
text
text
 
 
textedit
textedit
 
 
theme
theme
 
 
ui
ui
 
 
.gitignore
.gitignore
 
 
.golangci.yml
.golangci.yml
 
 
CODE_OF_CONDUCT.md
CODE_OF_CONDUCT.md
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
activate_darwin.go
activate_darwin.go
 
 
activate_other.go
activate_other.go
 
 
app_frame.go
app_frame.go
 
 
app_gpu.go
app_gpu.go
 
 
app_js.go
app_js.go
 
 
app_stub.go
app_stub.go
 
 
clipboard_image_darwin.go
clipboard_image_darwin.go
 
 
clipboard_image_other.go
clipboard_image_other.go
 
 
frame_input.go
frame_input.go
 
 
frame_input_test.go
frame_input_test.go
 
 
go.mod
go.mod
 
 
go.sum
go.sum
 
 
resources.go
resources.go
 
 
scroll_darwin.go
scroll_darwin.go
 
 
scroll_darwin_test.go
scroll_darwin_test.go
 
 
scroll_other.go
scroll_other.go
 
 
surface_layer_darwin.go
surface_layer_darwin.go
 
 
surface_layer_other.go
surface_layer_other.go
 
 
window_chrome_darwin.go
window_chrome_darwin.go
 
 
window_chrome_other.go
window_chrome_other.go
 
 
window_hints_darwin.go
window_hints_darwin.go
 
 
window_hints_other.go
window_hints_other.go
 
 
window_host.go
window_host.go
 
 
yoga.go
yoga.go
 
 
zoom.go
zoom.go
 
 
zoom_test.go
zoom_test.go
 
 

Repository files navigation

Yoga

Yoga

Website and docs · Code editor

A from-scratch, cross-platform UI framework in Go (module github.com/yogaui/yoga, Go 1.26.2). It renders with WebGPU (desktop via GLFW + wgpu-native; browser via WASM) and lays out with a pure-Go flex/grid/stack engine.

This README is the human guide to building UI with Yoga. AI agents should also load the project skill at .cursor/skills/yoga-ui/.

Demos

go run ./example/todo        # smallest app (todos)
go run ./example/catalog     # component gallery (sidebar + showcases)
go run ./example/chapar      # multi-page nav shell

# Headless (no window / GPU) — same UI pipeline, for CI
go run -tags nogpu ./example/todo
go build ./... && go build -tags nogpu ./... && go test ./...

There is no Makefile. -tags nogpu is the only special Go build flag: it swaps GPU/GLFW files for stubs. Use the yoga CLI for packaging (web, DMG, AppImage, zip).

Command What it shows
example/todo Form + list, controlled TextField / Checkbox
example/catalog Sidebar catalog of widget categories; custom title bar (CustomTitleBar)
example/chapar App chrome: top bar, nav, pages as Layout helpers

Packaging CLI

Install and use the yoga tool to build distributables:

go install github.com/yogaui/yoga/cmd/yoga@latest
# or from this repo:
go run ./cmd/yoga package -os web ./example/todo
Command Output
yoga package -os web dist/web/ — index.html, app.wasm, wasm_exec.js, yoga_loader.js
yoga package -os darwin Name.app + DMG and/or PKG (see [darwin] in yoga.toml)
yoga package -os linux tar.gz or tar.xz (+ AppImage if appimagetool is on PATH)
yoga package -os windows portable .zip with a GUI-subsystem .exe carrying the icon, DPI manifest and version info
yoga serve [dir] static server (default dist/web)
yoga run go run the app on the host
yoga build -os … compile only into dist/<os>/

An app can pin the CLI next to the framework with go get -tool github.com/yogaui/yoga/cmd/yoga and run it as go tool yoga ….

Optional yoga.toml in the app directory:

name = "Todos"
id = "com.example.todo"
version = "0.1.0"                 # -version v1.2.0 overrides (a leading v is dropped)
main = "."
icon = "assets/icon.png"          # PNG; Windows embeds it, macOS converts it to .icns
# Artifact name without extension. {name} {version} {os} {platform} (macos|linux|windows) {arch}
artifact = "todos-{platform}-v{version}-{arch}"

[build]
ldflags = "-s -w -X main.version={version}"
tags = []
flags = ["-trimpath"]

[window]
title = "Todos"

[darwin]
icon = "assets/icon.icns"         # optional: a hand-made .icns instead of the PNG
display_name = "Todos"
copyright = "Copyright © 2026"
category = "public.app-category.productivity"
min_system = "13.0"               # LSMinimumSystemVersion and the C deployment target
bundle_version = "1"
formats = ["dmg", "pkg"]          # pkg for App Store upload when signed
notarize = false                  # or -notarize; needs a signing identity

[darwin.dmg]
background = "assets/dmg-background.png"
volume_name = "Todos"
volume_icon = "assets/icon.icns"
window_pos = [100, 100]
window_width = 660
window_height = 400
icon_size = 128
app_pos = [180, 200]
applications_pos = [480, 200]

[darwin.sign]
identity = "Developer ID Application: …"
installer_identity = "3rd Party Mac Developer Installer: …"
entitlements = "assets/entitlements.plist"

[linux]
binary = "todos"                  # executable name in the archive
format = "tar.xz"                 # tar.gz (default) or tar.xz (needs xz)
[linux.files]                     # archive path = source; replaces the generated .desktop/icon
"LICENSE" = "LICENSE"
"install.sh" = "packaging/install.sh"

[windows]
console = false                   # true keeps the console window
company = "Example"
description = "Todos"
[windows.files]                   # zip path = source, next to the exe
"LICENSE.txt" = "LICENSE"

CLI overrides: -id, -format dmg,pkg, -version, -ldflags (appended), -build-number, -sign, -installer-sign, -entitlements, -notarize.

-arch universal (darwin) builds amd64 and arm64 and joins them with lipo. Without a signing identity the .app is ad-hoc signed so it runs locally. -notarize zips the signed app, submits it with notarytool --wait and staples the ticket before the DMG is made; it reads NOTARY_KEYCHAIN_PROFILE, or APPLE_ID, APPLE_TEAM_ID and APPLE_APP_SPECIFIC_PASSWORD, from the environment.

Web requires a browser with WebGPU (navigator.gpu). Desktop packaging needs CGO (GLFW / wgpu-native) and generally must run on the target OS.

go run ./cmd/yoga package -os web ./example/todo
go run ./cmd/yoga serve -addr 127.0.0.1:8080          # serves ./dist/web
go run ./cmd/yoga serve ./path/to/web-output          # or any packaged dir
# open http://127.0.0.1:8080/

Screenshots

The component catalog (go run ./example/catalog) in the default yoga-dark theme:

Catalog surfaces: borders, cards, alerts, and badges

Catalog form rows Command palette

Mental model

Yoga is retained app state + a declarative tree rebuilt every frame (the SwiftUI @State analogue):

  1. Your app is a struct that implements yoga.App — one method, Body(c *ui.Ctx) ui.View.
  2. Body runs on every drawn frame. There is no framework-level widget cache.
  3. Durable state (strings, slices, editors, tables) lives on the app struct.
  4. Micro-state (hover, caret, scroll, open menus) lives in c.Widget(id, …), keyed by a unique id.
  5. ui.View is Layout(c *ui.Ctx) *layout.Element. The DSL (Column, Button, …) returns *ui.Node, which implements View.

Do not keep *ui.Ctx after Body returns. The runtime owns it and resets it each pass.

The event loop is idle until input or an animation request, so idle CPU stays near zero. Each drawn frame builds the tree twice: once to hit-test input against fresh geometry, then again so paint reflects state those events changed.

First window

yoga.Run creates the window and text engine, then calls build. Construct anything that measures text (editors, tables) inside build, never before Run.

package main

import (
	"github.com/yogaui/yoga"
	"github.com/yogaui/yoga/ui"
)

type App struct {
	name string
}

func Build() *App { return &App{} }

func (a *App) Body(c *ui.Ctx) ui.View {
	th := c.Theme()
	return ui.Column(
		ui.Title("Hello"),
		ui.TextField("name", a.name).
			Placeholder("Your name").
			OnChange(func(s string) { a.name = s }).
			DefaultFocus().
			Grow(1),
		ui.Button("ok", ui.Text("OK")).Primary().OnClick(func() {}),
	).Gap(th.Spacing.M).Padding(th.Spacing.L).Grow(1).Background(ui.TokenSurface)
}

func main() {
	cfg := yoga.Config{
		Title:  "Hello",
		Width:  640,
		Height: 480,
	}
	if err := yoga.Run(cfg, Build); err != nil {
		panic(err)
	}
}

Custom title bar (VS Code-style): set CustomTitleBar: true in yoga.Config, then put menus and tools in ui.TitleBar(...) at the top of Body. macOS keeps native traffic lights; Windows and Linux get framework min/max/close buttons. Empty title-bar area drags the window; double-click toggles maximize. See example/catalog.

cfg := yoga.Config{
	Title:          "My App",
	Width:          1100,
	Height:         720,
	CustomTitleBar: true,
}

func (a *App) Body(c *ui.Ctx) ui.View {
	return ui.Column(
		ui.TitleBar(
			ui.Dropdown("file", "File", fileItems),
			ui.Spacer(),
			ui.TextField("q", a.query).Placeholder("Search…").Width(240),
		),
		mainContent(c).Grow(1),
	).Grow(1).Background(ui.TokenSurface)
}

Child widgets inside TitleBar auto-size to th.Metrics.TitleBarControlHeight (26px) and sit vertically centered in the 36px bar — no need to set .Height() on each control.

Ship a GPU main (//go:build !nogpu) and a headless main (//go:build nogpu) in the same package, as the demos do.

Optional capabilities (detected by type assertion):

  • Close() — stop workers / close files when the window closes.
  • OnKey(c *ui.Ctx, k input.KeyEvent) bool (yoga.KeyHook) — app-global shortcuts before focus routing; return true to consume.

Building a tree

The ergonomic API is package ui.

Layout

Constructor Layout
ui.Column(children...) Vertical flex (children stretch on the cross axis)
ui.Row(children...) Horizontal flex (children vertically centered)
ui.Stack(children...) Layered (z-order)
ui.Center(child) Fill parent, center child
ui.Spacer() Flex-grow filler
ui.Grid(cols, children...) Equal-width columns
ui.Scroll(id, child) Clip and scroll; id remembers offset
ui.ViewOf(v) Wrap any View so modifiers chain
ui.Raw(el) Wrap a bare *layout.Element
ui.HLine / ui.VLine Rules
ui.Icon(icon, size, color) Atlas sprite
ui.Image(id, data) PNG/JPEG bitmap (ImageFile, ImageFS)
ui.SVG(id, data) Custom SVG (SVGFile, SVGFS; currentColor follows text color)
ui.TitleBar(children...) Custom window title bar; platform controls auto-included
ui.WindowControls() Min/max/close for undecorated windows (usually via TitleBar)

Children are ui.View. nil is skipped. Split UI into helpers that return ui.View.

Chain modifiers on *ui.Node:

.Gap .Padding .PaddingXY .PaddingLeft/Right/Top/Bottom
.Margin .MarginXY .MarginLeft/Right/Top/Bottom
.Wrap .Grow .Shrink .Width .Height .Frame .Size
.Align .Justify .Style .Background .BackgroundColor
.Disabled .DefaultFocus

Alignment: ui.AlignStart|Center|End|Stretch, ui.JustifyStart|Center|End|Between.

.Float(corner, dx, dy) takes a node out of the flow and pins it to a corner of its parent, over the siblings before it — a button in the corner of an editor, for example:

ui.Column(
	ui.ViewOf(editor).Grow(1),
	ui.Button("fmt", ui.Text("Format")).Float(ui.CornerBottomRight, 22, 22),
).Grow(1)

A pane that should fill leftover space needs .Grow(1) on itself and every ancestor up to the Body root. Root trees almost always end with .Grow(1).Background(ui.TokenSurface). A Row whose children should stretch vertically needs .Align(ui.AlignStretch).

Use c.Theme().Spacing (XXS 2px … XXXL 32px) instead of magic numbers. Typical: S 8, M 12, L 16.

Controls are controlled

Pass the current value every frame. Callbacks write back to the app struct. Give every interactive widget a stable unique id (hover/caret/scroll are stored under that key).

ui.TextField("url", app.url).
    Placeholder("https://…").
    IconStart(icons.Search).
    OnChange(func(s string) { app.url = s }).
    OnSubmit(app.fetch).
    Grow(1)

ui.Button("send", ui.Text("Send")).Primary().Hint("⌘↵").OnClick(app.fetch)
ui.Checkbox("notify", "Notify").Check(app.notify).OnToggle(func(v bool) { app.notify = v })
ui.Radio("ra", "A").Check(app.mode == 0).OnClick(func() { app.mode = 0 })
ui.Select("lang", opts).Width(200).Selected(i).OnChange(func(v string) { app.lang = v })

A text field can also mark up its own text and finish it for the user. .Highlight(fn) colors byte ranges of the value — template placeholders, matches, tokens — and .Suggest(fn) opens a completion popup under the field, driven by ↑ ↓ Enter/Tab and Escape:

ui.TextField("url", app.url).
    Highlight(func(v string) []ui.TextSpan { return app.vars.Spans(v) }).
    Suggest(func(v string, caret int) ([]ui.Suggestion, int, int) {
        // Candidates, plus the byte range they replace.
        return app.vars.Complete(v, caret)
    })

.HoverInfo(fn) adds the third piece: a card explaining whatever the pointer rests on, returning a HoverCard{Title, Body, Start, End} whose range the card is anchored under.

Table offers all three per cell through CellHighlight, CellSuggest, and CellHoverInfo. A masked (password) value is never highlighted, completed, or explained, so none of the hooks can leak it.

Button variants: default Secondary; .Primary(), .Subtle(), and .Ghost(). Ghost is text-like (no padding or chrome) for footers and status bars; chain .HoverFill() for a hover background. Supports .IconStart() and .Tooltip(). Icon-only: ui.IconButton(id, icons.Settings).

Typography: Text, Title, Subtitle, Caption, Strong, Muted. Color inherits from the parent (for example a button’s label uses the button’s text token) unless you override with .Style(ui.Spec{}.TextColor(ui.TokenForegroundMuted)).

Heavy widgets: construct once

Table, Tree, FileTree, and ListView keep real state. Build them in Build*, then place them with ui.ViewOf:

func Build() *App {
	app := &App{}
	app.table = ui.NewTable(cols, actions)
	return app
}

func (a *App) Body(c *ui.Ctx) ui.View {
	return ui.Column(
		ui.ViewOf(a.table).Grow(1),
	).Grow(1)
}

Constructing these inside Body resets caret, scroll, and selection every frame.

Code editor

The code editor (Tree-sitter highlighting, language servers, find and replace, folding, multiple cursors) lives in its own module, github.com/yogaui/editor, so apps that do not need it skip its Cgo grammars. It is a heavy widget like the ones above:

import "github.com/yogaui/editor"

app.editor = editor.NewEditorFor("main.go", src) // in Build
ui.ViewOf(app.editor).Grow(1)                    // in Body

Markdown code blocks are colored through the syntax registry. The core ships no grammars, so fences stay plain until something registers them; importing github.com/yogaui/editor/highlight (the editor does) registers its highlighters.

Text widgets of your own can share TextInput's editing rules (word motion, multi-click timing, undo grouping) through the textedit package.

Splitter, drawer, tabs, nav, menus

// Requires yoga.Config{CustomTitleBar: true} at window creation.
ui.TitleBar(
	ui.Dropdown("file", "File", []ui.MenuItem{{Label: "Save", OnSelect: save}}),
	ui.Spacer(),
	ui.TextField("q", query).Placeholder("Search…").Width(240),
)
// macOS: native traffic lights + leading inset. Windows/Linux: trailing WindowControls.
// Drag empty area to move; double-click toggles maximize.

ui.Splitter("split", ui.Horizontal, sidebar, main).Sizes(240, 0).Grow(1)
// 0 = flex; drag sizes persist under the id. Axis: Horizontal | Vertical.

ui.Drawer("inspector", panel, page).Open(open).Edge(ui.EdgeRight).Overlay().Size(320).Grow(1)
// .Push() shrinks page; .Modal(true) adds scrim (overlay); .Swipe(true) for drag open/close.
// Panel view should use .Grow(1); drawer owns main-axis size and clips overflow.
// Nest drawers for IDE-style panels (e.g. bottom terminal + right chat).

ui.Tabs("tabs", tabs).Selected(i).OnSelectItem(onSelect).OnTabClose(onClose).
    OnTabContextMenu(func(i int) []ui.MenuItem { … }) // right-click: Close / Close Others / …
// Too many tabs: the strip scrolls (wheel/trackpad), keeps the active tab in view,
// and a "+N ⌄" button at the right edge lists the hidden tabs.
// Section switcher without close buttons:
ui.Tabs("sections", tabs).Selected(i).OnSelectItem(onSelect).Closable(false)
// Per-tab state: TabModel{Busy: true} shows a spinner in place of the icon,
// TabModel{Status: th.Warning} a colored dot after the title.

ui.Nav("nav", ui.NavVertical, ui.NavIconTop, items...).
    Selected(i).OnSelectItem(func(i int, id string) { … }).Width(88)

ui.Dropdown("file", "File", []ui.MenuItem{{Label: "Save", OnSelect: save}})
ui.MenuButton("export", "Export", items).Primary().IconStart(icons.Save) // click opens menu
ui.MenuButton("save", "Save", items).Primary().OnClick(save)        // split: label=action, chevron=menu
ui.IconButton("more", icons.Ellipsis).Menu(items)                   // icon only, menu under its right edge
// MenuItem{Icon: icons.Trash2, Danger: true} adds a leading icon and the error color.

ui.ClickableCard("p1", "Project", "Description", body).OnClick(open).
    Actions(ui.IconButton("p1-more", icons.Ellipsis).Menu(items)).    // title-row slot
    Footer(ui.Caption("3 sessions"))

Dialogs and toasts

Window-owned hosts on Ctx. BuildFrame lays them out — do not put them in Body:

c.Toasts().Show("Saved", ui.ToastInfo, 3*time.Second)
c.Dialogs().ShowInfo("Info", "helpful note", nil)
c.Dialogs().ShowWarning("Warning", "check before continuing", nil)
c.Dialogs().ShowError("Error", "request failed", nil)
c.Dialogs().ShowAction("Delete?", "This cannot be undone.", onYes, onNo)
c.Dialogs().ShowDanger("Remove?", "This cannot be undone.", "Remove", onRemove)
c.Dialogs().ShowInput("Name", "placeholder", onOK, onCancel)

c.Dialogs().Show(ui.DialogOpts{
	Title:  "Settings",
	Width:  720,
	Height: 520,
	Body: func(c *ui.Ctx) ui.View {
		return ui.Row(
			ui.Nav("cats", ui.NavVertical, ui.NavIconLeft, items...).Width(200),
			ui.VLine(th.Stroke.Thin, th.Border),
			ui.Scroll("form", ui.Form("settings", rows...)).Grow(1),
		).Align(ui.AlignStretch).Grow(1)
	},
	Actions: []ui.DialogAction{{Label: "Close", Primary: true}},
})

Custom dialogs use the same overlay/modal behavior as the file picker. Escape runs OnDismiss. Footer actions close the dialog before OnClick.

Form and Switch

ui.Form renders labeled settings rows (icon, title, description, control):

ui.Form("prefs",
	ui.FormSwitch("notify", "Notifications", "Show alerts", on, func(v bool) { on = v }),
	ui.FormSelect("theme", "Theme", "Color scheme", opts, idx, onChange),
	ui.FormNumber("size", "Font size", "Editor size in pt", 14, 10, 24, 1, onSize),
	ui.FormText("file", "Default file", "Open on startup", name, onName),
	ui.FormFile("cert", "Certificate", "PEM for TLS", path, filters, onPath),
)

FormFile opens the window's file dialog (c.Files()) in the current file's folder; the button shows the file name, and a clear button passes "" to the callback. Descriptions wrap to the width the control leaves.

ui.FormHeading(title, desc) opens a group of rows. Set Optional on an item to tag its label "Optional", and Placeholder to say what an empty text or file row means (the file button shows it instead of "Choose file…").

ui.Switch(id).Check(on).OnToggle(fn) is an unlabeled pill toggle for compact rows.

File dialog

Pure-Go file/folder picker (ui.FileDialog) — no native OS dialogs. Call c.Files().Show with options:

c.Files().Show(ui.FileDialogOpts{
	Mode: ui.FileDialogOpenFile, // FileDialogOpenFolder | FileDialogSaveFile
	Title: "Open File",
	Dir: "/path/to/start", // optional; defaults to home
	Multiple: false,
	Filters: []ui.FileFilter{
		{Label: "Go files", Exts: []string{".go"}},
		{Label: "All files", Exts: nil},
	},
	ShowHidden: false,
	ShowSaveFilter: true,    // file-type filter in save mode (default off)
	AllowCreateFolder: true, // New Folder button in the footer
	OnConfirm: func(paths []string) { … },
	OnCancel: func() { … },
})

Modes. FileDialogOpenFile lists files (double-click or Open confirms). FileDialogOpenFolder selects folders only. FileDialogSaveFile adds a filename field; Save confirms the path and applies the selected filter extension when the name has none.

Layout. Places sidebar, breadcrumb + searchable file table in the main pane, and a footer with filename (save mode), file-type filter, optional New Folder (next to Cancel/Save), and Cancel + Open/Select/Save. When creating a folder, an inline name field with Create/Cancel appears in the footer.

Keyboard. Escape cancels. Enter confirms when valid. Tab cycles within the modal dialog.

See example/gallery/gallery.go in yogaui/editor for open file, multi-select, folder pick, save, and a settings dialog demo.

Theme

There is one live *theme.Theme (theme.Current()). theme.Use("yoga-light") overwrites it in place, so the next paint picks up the new palette with no rebuild.

Prefer tokens (ui.TokenSurface, ui.TokenChrome, ui.TokenForeground, ui.TokenAccent, ui.TokenBorder, ui.TokenError, …) over literal colors so chrome follows the theme.

ui.Column(...).Background(ui.TokenChrome)
ui.Text("status").Style(ui.Spec{}.TextColor(ui.TokenForegroundMuted))

Default theme is yoga-dark. If you switch before opening the window, call theme.Use before yoga.Run.

Shipped names: yoga-dark, yoga-light, system, yoga-high-contrast, yoga-high-contrast-light, yoga-colorblind-dark, yoga-colorblind-light, yoga-midnight, github-dark, github-light, catppuccin, catppuccin-latte, dracula, nord, solarized-dark, solarized-light, gruvbox-dark, gruvbox-light, monokai, tokyo-night, tokyo-night-day, one-dark, one-light, everforest-dark, everforest-light (theme.Names()).

Use theme.Use("system") to follow the platform dark/light setting; the runtime re-syncs each frame. theme.Selected() returns "system" while that mode is active; theme.Current() holds the resolved palette.

theme.UseSystem(name) follows the OS appearance within a theme family, so a reader on catppuccin gets catppuccin-latte in daylight instead of being moved to the yoga palette. Each theme names its counterpart through LightSibling / DarkSibling; themes with no counterpart stay put.

Two themes exist for accessibility rather than taste: yoga-high-contrast-light for readers who need maximum contrast on a light workspace, and the yoga-colorblind-* pair, whose status colors come from the Okabe-Ito palette so Error, Warning and Success stay separable without color vision.

Every shipped palette is checked against WCAG 2.1 AA by theme's contrast tests: 4.5:1 for text on every surface it can land on, 3:1 for control outlines and focus rings. Tokens that are defined by a contrast relationship rather than by taste — BorderControl, FocusRing, the *Foreground / *Surface status pairs, and the editor washes — are derived from the palette in normalize, so a custom theme only sets its brand colors and still passes. Use theme.ContrastRatio to check your own.

To write a theme, pick a 12-step neutral ramp, an accent and three status colors, and let theme.FromPalette derive the rest — the result meets the same contrast targets as the shipped themes:

t := theme.FromPalette(theme.Palette{
	Name: "acme-dark", Dark: true,
	// sunken, surface, chrome, chrome-muted, overlay, border,
	// hover, pressed, subtle, muted, disabled, text
	Neutral: theme.Ramp{ /* 12 colors, darkest to lightest */ },
	Accent:  render.RGBA8(53, 103, 214, 255),
	Error:   render.RGBA8(229, 72, 77, 255),
	Warning: render.RGBA8(245, 185, 74, 255),
	Success: render.RGBA8(70, 184, 100, 255),
})
theme.Register(t)
theme.Use("acme-dark")

For text, always use the *Foreground status tokens (th.ErrorForeground), never the raw th.Error hue: an amber Warning cannot reach 4.5:1 on a light surface. Draw focus rings through th.FocusRingOn(fill) rather than reading th.FocusRing, so the ring stays visible on accent-filled controls.

Spacing, radius, stroke, and type ramps live on c.Theme() (th.Spacing.M, th.Radius.Medium, th.Stroke.Thin, th.Typography.Body).

Icons are pre-rasterized Lucide symbols from github.com/yogaui/yoga/icons (e.g. icons.Search, icons.Plus, icons.ChevronDown). Unused icons are dropped by the Go linker. The full catalog lives in icons/catalog for the component gallery. Regenerate with go run ./cmd/generate-lucide. Custom SVGs: render.RegisterIcon(name, svg) before first draw.

Lucide is licensed under the ISC License.

Input, focus, overlays, async

  • Focus. Interactive DSL widgets register themselves. Tab order is Layout order. .DefaultFocus() / c.Focus().EnsureFocus(w) picks a fallback when nothing is focused. Open dialogs call BeginModal then SetModal so Tab and keys stay inside the dialog.
  • Overlays. Menus, selects, dialogs, and toasts call c.Overlay(el). Overlays paint and hit-test on top of the body.
  • Animation. c.Animate(d) schedules a repaint within d (caret blink, spinner, polling). The runtime waits the minimum requested duration, or sleeps until the next OS event.
  • Background work. Safe to call c.Invalidate() from any goroutine (a job finished, HTTP returned). Typical pattern: a result channel drained at the top of Body, plus c.Animate(30*time.Millisecond) while a request is in flight.
  • Shortcuts. Read c.Keyboard() in Body, or implement yoga.KeyHook when a focused widget would otherwise eat the key.
  • File drops. c.Mouse().Dropped holds the paths of files dropped on the window this frame, at the pointer position. Set it to nil once taken.
  • Clipboard images. c.Clipboard() may also be an input.ImageClipboard; GetImage() returns the clipboard's picture as PNG. It works on macOS, and on Linux when wl-paste or xclip is installed. MemClipboard.SetImage fills it in tests.

Pointer handlers set m.Consumed = true to stop bubbling. Overlay hit-testing runs first.

Custom widgets

Most screens are functions that return ui.View. For a retained component, implement ui.View:

func (p *Page) Layout(c *ui.Ctx) *layout.Element {
	return ui.Column(/* … */).Grow(1).Layout(c)
}

Chapar-style pages return ui.View from a helper also named Layout and are composed by the shell — that helper is not the ui.View interface (which must return *layout.Element).

Low-level drawing: layout.New(layout.Box().…, children…), attach Paint / OnMouse, wrap with ui.Raw. Hit-test with e.Frame.Contains(m.X, m.Y).

Headless / tests

text, _ := shape.NewEngine(1, false)
clip := &input.MemClipboard{}
sheet := render.NewSpriteSheet(text.Atlas)
yoga.SetResources(text, sheet, clip)

c := ui.New(text, ui.NewFocusScope(), nil)
c.SetIcons(sheet)
c.SetClipboard(clip)

root := ui.BuildFrame(c, app.Body, w, h, mouse, keyboard)
layout.Dispatch(root, mouse)
c.Focus().Route(keyboard)
mouse.EndFrame()
keyboard.EndFrame()
root = ui.BuildFrame(c, app.Body, w, h, mouse, keyboard)
layout.Paint(root, drawList, text)

Architecture

Dependency direction is strictly downward:

example/*             app: Body(c) trees
  yoga                runtime: window, WebGPU, fonts, event loop
    ui                View DSL, Ctx, focus, widget store
      layout  theme   Element tree, flex/grid/stack, design tokens
        render        DrawList, atlas, WGSL
          input text syntax textedit   mouse/kb, piece table, token classes, editing rules

Cgo exists in the desktop GPU path (app_gpu.go, GLFW + wgpu-native) and macOS title-bar chrome. The browser path (app_js.go, GOOS=js) uses browser WebGPU via cogentcore’s JS bindings and skips CGO. Everything above the platform host is pure Go. layout.Element is the node type; Calculate solves then flattens to absolute Frames; Dispatch delivers mouse events front-to-back.

Agent skill

For Cursor (and any agent you paste into):

  • .cursor/skills/yoga-ui/SKILL.md — rules and bootstrap
  • .cursor/skills/yoga-ui/widgets.md — constructors
  • .cursor/skills/yoga-ui/examples.md — patterns from example/

License

Yoga is released under the MIT License. Contributors are expected to follow the Code of Conduct.

About

A from-scratch, cross-platform UI framework in Go, drawn with WebGPU on desktop and in the browser.

yogaui.github.io

Topics

cross-platformdesktopgogolangguiui-frameworkwasmwebgpu

Resources

Readme
MIT license

Code of conduct

Code of conduct
Activity
Custom properties

Stars

18 stars

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.